+ All Categories
Home > Documents > Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Date post: 25-Dec-2015
Category:
Upload: laureen-dawson
View: 243 times
Download: 2 times
Share this document with a friend
Popular Tags:
32
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns
Transcript
Page 1: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Design Patterns

CS 124

Reference: Gamma et al(“Gang-of-4”), Design Patterns

Page 2: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Pattern: some definitions

a combination of qualities, acts, tendencies, etc., forming a consistent or characteristic arrangement: the behavior patterns of teenagers.

an original or model considered for or deserving of imitation: our constitution has been a pattern for those of many new republics.

anything fashioned or designed to serve as a model or guide for something to be made: a paper pattern for a dress.

Definitions extracted from dictionary.com

Page 3: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Design Pattern

The notion of pattern as it applies to OO software development

Solution to a particular kind of problem How to combine classes and methods Based on design experience Use requires understanding of the appropriate

problem and being able to recognize when such problems occur

Reuse solutions from the past It is not code reuse, it is experience reuse

Page 4: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Patterns in other professions

Other professions have developed patterns and jargon for these well-tested patterns

Example: writers/novelists: “Tragically-flawed hero”, “romantic novel”

Other professions Architects/building engineers Con-artists (see Ocean’s 11 movies)

Page 5: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Design Patterns: the highest form of reuse and abstraction

Specific concrete Code Code Snippets Functions / Methods

Generalized and Reusable Code Classes, Templates, Code library, API

Reusable concepts Data Structures, Algorithms

Patterns How / When to apply these concepts, Design Patterns

Page 6: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Design Patterns Name Intent/Problem

Situation (problem) and context When to apply the pattern; conditions

Solution Elements that make up the design, relationships,

collaboration; more a template rather than a concrete solution

How the general arrangement classes and objects solves it UML diagrams (class relationships and responsibilities)

Consequences variations, tradeoffs, cost-benefit

Page 7: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

How to select design patterns

Consider how the design patterns solve design problems

Scan intent section Consider how patterns interrelate Study patterns of like purpose Examine cause of redesign Consider what should be variable in design (what

you might want to change without redesign): Encapsulate the concept that varies

Page 8: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

How to use a design pattern

Read up on the pattern Study structure, collaboration, participants Look at sample code Choose names of participants meaningful in the

application context Define classes Define application specific names for operations in

the process Implement the operations

Page 9: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Some Patterns for Discussion

Singleton Factory Method Adaptor Iterator

Page 10: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Singleton Intent

ensure a class has only one instance, and provide a global point of access to it

Motivation Important for some classes to have exactly one instance.

E.g., although there are many printers, should just have one print spooler

Ensure only one instance available and easily accessible global variables gives access, but doesn’t keep you from

instantiating many objects Give class responsibility for keeping track of its sole

instance

Page 11: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Design Solution

Defines a getInstance() operation that lets clients access its unique instance

May be responsible for creating its own unique instance

Singleton

-uniqueinstanceSingleton data…

+getInstance()Singleton methods…

Recall that an underlined method means “static”

Page 12: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Singleton Example (Java)

Database

Database

-Database DBinstance attributes…

+Database getDB()instance methods…

public class Database {private static Database DB; ...private Database() { ... }public static Database getDB() { if (DB == null) DB = new Database(); return DB;} ...}

In application code…Database db = Database.getDB();db.someMethod();

Page 13: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Implementation Declare all of class’ constructors private

prevent other classes from directly creating an instance of this class

Hide the operation that creates the instance behind a class operation (getInstance)

Variation: Since creation policy is encapsulated in getInstance, possible to vary the creation policy

Page 14: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Singleton Consequences

Ensures only one (e.g., Database) instance exists in the system

Can also use this pattern to control fixed multiple instances

Much better than the alternative: global variables

Page 15: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Factory Method

Intent: provide an interface for creating objects without specifying their concrete classes

Example: Stacks, Queues, and other data structures Want users to not know or care how these structures are

implemented (separation) Example: UI toolkit to support multiple look-and-feel

standards, e.g., Motif, PM Abstract class for widget, supporting class for specific

platform widget

Page 16: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Design Solution forFactory Method

Factory

createProduct():Product

<<interface>> Product

abstract methods

ConcreteProdA

methods

ConcreteProdB

methods

Client

Note: this is anabbreviated design

Page 17: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Participants Factory

implements the operations to create concrete product objects

(Abstract) Product: declares an interface for a type of product object

Concrete Product defines a product object to be created by the

corresponding concrete factory implements the abstract product interface

Client: uses only Factory and Abstract Product

Page 18: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Factories in Java

Stack is an Interface ArrayStack and LinkedStack implement Stack StackFactory returns objects of type Stack through

its factory methods Select the appropriate concrete Stack class class

If using info from requesting client, can hardcode selection logic and choice of product objects

Use Hashed Adapter Pattern to separate selection logic for factories from the data it uses to make the selection

Page 19: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Factory Method Consequences

Factory class or method can be altered without affecting the application Concrete classes are isolated

Factory class can be responsible for creating different types of objects e.g., DataStructure factory that returns stacks,

queues, lists, etc. “product families” (see Abstract Factory pattern) creational logic

determining object type based on certain criteria

Page 20: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Coupling One of the goals of Design Patterns is the idea of

loose-coupling or de-coupling reducing or removing class dependencies throughout the

system For example, Factory removes the dependency on the

specific subclasses generated by the Factory from the rest of the system

instead the system is dependent on the single interface type that is generated by the Factory

Loosely coupled or decoupled code is easier to reuse since the code has fewer dependencies on other code

Page 21: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Kinds of Patterns

Singleton and Factory Method are examples of Creational Patterns

Other kinds of patterns Structural: concerns object structure;

e.g., Adapter Behavioral: concerns object interaction and

distribution of responsibilities;e.g., Iterator

Page 22: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Adapter Intent: Adapter lets classes work together that couldn’t otherwise

because of incompatible interfaces.

Motivation: Sometimes, a class that is designed for reuse isn’t reusable only because its interface doesn’t match the domain-specific interface an application requires. e.g. drawing editor that allows users to draw and edit shapes.

Has a TextShape subclass that is hard to implement. Fortunately there are pre-existing classes like TextView that implements the complexities; problem is incompatibility.

It would not make sense if we have to modify the reusable class so as to conform to the client interface. Built-in; no source code

Page 23: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Two forms of the Adapter Pattern

Object Adapter pattern Concerned with object composition. Implements the interface that the client expects and

creates an adaptee instance within the adapter class Implements client’s methods by making calls to a

physical instance of the adaptee object.

Client Expected

+ expectedMethod()

ObjectAdapter

+ void : expectedMethod()

- Adaptee : adaptee

void expectedMethod() { adaptee.specificMethod();}

1 Adaptee

+ void : specificMethod()

1

Page 24: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Two forms of the Adapter Pattern

Class Adapter Pattern A class adapter uses multiple inheritance to adapt one

interface to another. Inherits the client interface and the adaptee’s

implementation.

Client Expected

+ expectedMethod()

ClassAdapter

+ void : expectedMethod()+ void : specificMethod()

void expectedMethod() { specificMethod();}

1 Adaptee

+ void : specificMethod()

Page 25: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Comparison of Applicability & Consequences

Use adapter pattern when: Using an existing class that does not match with the one you

need (object adapter only) reusing several existing class

Impractical to adapt each by subclassing every one of them

Consequences:

Object Adapter- Lets a single adapter work with

many adaptees (adaptee itself and subclasses)

- Harder to override adaptee behavior

Class Adapter- Class adapter won’t work with

adaptee’s subclasses- Easier to override adaptee’s behavior,

since adapter is a subclass of adaptee- Can have unforseen consequences,

Adapter can be placed anywhere the Adaptee can due to inheritance

Page 26: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Iterator Pattern

Intent: provide a way to access the elements of an aggregate object sequentially without expressing its underlying representation

Example: iterators for Java collections or C++ STL containers Note that you can have several iterator objects for

a container and that the iterators are separate classes

Page 27: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

<<interface>>Collection

iterator() : IteratorIF…

<<interface>>IteratorIF

hasNext() : booleannext() : Item

Collection IteratorFetches from

Creates

Page 28: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Iterators in Java

Iterators are used a lot with Java collection objects e.g. Lists, Sets and Maps

By calling the iterator() method on the List/Set or on the result of Map.values() you can go through all the elements via the next() method

Note: order of insertion is not necessarily going to be followed by the iterator, it only guarantees that everything will come out.

Page 29: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Creational Patterns

Abstract Factory Builder Factory Method Prototype Singleton

Page 30: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Structural Patterns

Adapter Bridge Composite Decorator Façade Flyweight Proxy

Page 31: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Behavioral Patterns

Chain of Responsibility Command Interpreter Iterator Mediator Memento And a few more …

Page 32: Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.

Summary

Main point: to recognize that there are proven solutions to problems that a designer/ programmer may encounter Solutions are results of others’ experiences Towards “standard approaches”

Search for such solutions first Although there is some merit attempting to create the

solution yourself

Becoming a design architect Up Next: More patterns


Recommended