1 design patterns software design and development
TRANSCRIPT
1
Design Patterns
Software Design and Development
2
Outline
Definition and Description of a Design Pattern
Discussion of Selected PatternsKinds of Patterns
Reference: Gamma et al (“Gang-of-4”), Design Patterns
3
Pattern
Describes a problem that has occurred over and over in our environment, and then describes the core of the solution of that problem in a way that the solution can be used a million times over, without ever doing it in the same way twice.
4
Design Pattern
Solution to a particular kind of problemHow to combine classes and methodsNot solve every problem from first
principlesBased on design experienceUse requires understanding of the
appropriate problem and being able to recognize when such problems occur
Reuse solutions from the past
5
Describing a PatternName Intent/Problem
Situation (problem) and contextWhen to apply the pattern; conditions
SolutionElements that make up the design, relationships,
collaboration; more a template rather than a concrete solution
How the general arrangement of elements (classes and objects) solves it
UML diagrams (class relationships and responsibilities) and code implications
6
Describing a Pattern
ConsequencesResults, variations, and tradeoffsCritical in understanding cost/benefit
7
How Design Patterns Solve Design Problems
Finding appropriate objectsDetermining object granularitySpecifying object interfacesSpecifying object implementationsPutting reuse mechanisms to workDesigning for change
8
Finding Appropriate ObjectsFactors involving decomposition of system
into objects (at times in conflicting ways)encapsulation, granularity, flexibility, performance,
evolution, reusability, etcDifferent approaches
Problem statement: nouns and verbs translate to classes and operations
Focus on collaborations and responsibilitiesModel real world (analysis) and translate to design
Many objects come from analysis model, but often have additional classes in design that have no counterpart in real world
9
Finding Appropriate Objects
Strict modeling of real world tends leads to system that reflect today’s realities, but not necessarily tomorrow’s
Abstractions that emerge during design are key to making design flexible
10
Determine Object Granularity
How to decide what should be an object?Different patterns have different approaches
represent complete subsystems as objectssupport huge numbers of objects at finest
granularitiescreate objects whose only responsibility is
creating other objectscreate objects whose responsibilities are to
implement a request on another object or group of objects
11
Specifying Object Interfaces
Interface: set of operation signaturescomplete set of requests that can be made to an
objectDoes not commit to implementation until run-
timeDefine interface by identifying key elements
and kinds of data that get sent across an interface
Specify relationships between interfaces require classes with similar interfacesplace constraints on interfaces
12
Specifying Object ImplementationsDefining internal state and implementation of
the operationClass vs Interface inheritance
Class: mechanism for code and representation sharing
Interface: describes when an object can be used in place of another
Distinction important for diff design patternsCommon theme: Variables not instances of
concrete classes; commit only to interface defined by an abstract class; use creational patterns to create instances
13
Reuse mechanisms
Inheritance vs compositionWhite box reuse: by subclassing
internals of parent visible to subclassesBlack box reuse: assembling or
composing objects to get more functionality
Both go together, but there is a tendency to overuse inheritance. Favor composition where possible
14
Designing for Change
Create objects indirectly instead of using class names (factory, abstract factory, prototype)
Avoid hard coding requests (chain of responsibility, command)
Limit platform dependencies (abstract factory, bridge)
Isolate algorithms that are likely to change (Builder, Iterator, Visitor, …)
Etc
15
How to select design patterns
Consider how the design patterns solve design problems
Scan intent sectionConsider how patterns interrelateStudy patterns of like purposeExamine cause of redesignConsider what should be variable in design
(what you might want to change without redesign): Encapsulate the concept that varies
16
How to use a design pattern
Read up on the patternStudy structure, collaboration, participantsLook at sample codeChoose names of participants meaningful
in the application contextDefine classesDefine application specific names for
operations in the processImplement the operations
17
Selected Patterns for Discussion
SingletonFactory MethodCompositeIterator
18
Singleton
Intent ensure a class has only one instance, and
provide a global point of access to itMotivation
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
19
Design Solution
Defines a getInstance() operation that lets clients access its unique instance
May be responsible for creating its own unique instance Singleton
static uniqueinstanceSingleton data
static getInstance()Singleton methods…
20
Singleton Example (Java)
Database
Database
static Database* DBinstance attributes…
static 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();
21
Singleton Example (C++)
class Database{private: static Database *DB; ... private Database() { ... }public: static Database *getDB() { if (DB == NULL) DB = new Database()); return DB; } ...}Database *Database::DB=NULL;
In application code…Database *db = Database.getDB();Db->someMethod();
22
ImplementationDeclare all of class’s 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
Subclassing: Variable that refers to singleton instance must get initialized with instance of the subclassuse registration
23
Singleton Consequences
Ensures only one (e.g., Database) instance exists in the system
Can maintain a pointer (need to create object on first get call) or an actual object
Can also use this pattern to control fixed multiple instances
Much better than the alternative: global variables
Permits refinement of operations and representation by subclassing
24
Abstract Factory
Intent: provide an interface for creating objects without specifying their concrete classes
Example: Stacks, Queues, and other data structuresWant 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, PMAbstract class for widget, supporting class for
specific platform widget
25
Solutions in C++
Use of header file (class declarations) and implementation file (method definitions) ok but limitedHeader file usually contains private declarations
which are technically part of the implementationChange in implementation requires that the
application using the data structure be recompiled
Alternative: create an abstract superclass with pure virtual data structure methods
26
Design Solution for Abstract Factory
Factory
createProduct()
Product
virtual methods
ConcreteProdA
methods
ConcreteProdB
methods
Client
Note: this is anabbreviated design
27
ParticipantsAbstract Factory
declares an interface for operations that create abstract product objects
Concrete Factory implements the operations to create concrete
product objectsAbstract Product
declares an interface for a type of product objectConcrete Product
defines a product object to be created by the corresponding concrete factory
implements the abstract product interface
28
Participants
Clientuses only interfaces declared by
AbstractFactory and AbstractProduct classes
29
Stack Example (C++)
Stack class defines virtual methodspush(), pop(), etc.
ArrayStack and LinkedStack are derived classes of Stack and contain concrete implementations
StackFactory class defines a createStack() method that returns a ptr to a concrete stackStack *createStack() { return new ArrayStack(); }
Client programs need to be aware of Stack and StackFactory classes only No need to know about ArrayStack()
30
Factories in Java
Stack is an InterfaceArrayStack and LinkedStack implement StackStackFactory returns objects of type Stack
through its factory methodsSelect class of the concrete factory it supplies to
client objectsIf using info from requesting client, can hardcode
selection logic and choice of factory objectsUse Hashed Adapter Pattern to separate selection logic
for concrete factories from the data it uses to make the selection
31
Abstract FactoryConsequences
Factory class or method can be altered without affecting the applicationConcrete classes are isolated
Factory class can be responsible for creating different types of objectse.g., DataStructure factory that returns
stacks, queues, lists, etc. “product families”
32
Abstract Factory Consequences
Promotes consistency among productsWhen products in a family are designed to work
together, it is important that an application use objects from only one family at a time. This pattern enforces this.
Supporting new kinds of products is difficult requires extending the factory interface (fixed
set)change AbstractFactory class and all the
subclasses
33
Composite Pattern
Intent: compose objects into tree structures to represent (nested) part-whole hierarchiesClients treat individual objects and
composition of objects uniformlyExample: GUIs (e.g., java.awt.*)
Buttons, labels, text fields, and panels are VisualComponents but panels can also contain VisualComponent objects
Calling show() on a panel will call show() on the objects contained in it
34
Structure
+Operation()+Add(Component)()+Remove(Component)()+GetChild(int)()
Component
+Operation()()
Leaf +Operation()()+Add(Component)()+Remove(Component)()+GetChild(int)()
Composite
-End11
-End2*
-End31
-End4*
-End5
1
-End6
*
Client-End7
*
-End8
*
35
Participants
Componentdeclares the interface for objects in the composition implements default behavior for interface common
to all classesdeclares interface for managing and accessing child
components (optional) defines interface for accessing a
component’s parent in the recursive structure Leaf
Leaf objects; primitives; has no childrendefine behavior for primitive objects
36
Participants
CompositeDefines behavior of components having
childrenStores child componentsImplements child-related operations in
the compositionClient
manipulates objects in the composition through the component interface
37
Consequences
Defines class hierarchies consisting of primitive objects and composite objects
Easy to add new kinds of components
Simple client – can treat primitives and composites uniformly
38
Iterator Pattern
Intent: provide a way to access the elements of an aggregate object sequentially without expressing its underlying representation
Example: iterators of C++ STL containersNote that you can have several iterator
objects for a container and that the iterators are separate classes
39
Motivation
Take responsibility for access and traversal out of the container object and into an iterator or Cursor object
Example
List
Count()Append(Element)Remove(Element)…
ListIterator
First()Next()IsDone()CurrentItem()
index
40
Consequences
Supports variations in the traversal of an aggregate
Simplifies the aggregate interfaceMore than one traversal can be
pending on one aggregate
41
Kinds of Patterns
CreationalObject creation; e.g., Factory and
SingletonStructural
Object structure; e.g., CompositeBehavioral
Object interaction and distribution of responsibilities; e.g., Iterator
42
Creational Patterns
Abstract FactoryBuilderFactory MethodPrototypeSingleton
43
Structural Patterns
AdapterBridgeCompositeDecoratorFaçadeFlyweightProxy
44
Behavioral Patterns
Chain Of ResponsibilityCommandInterpreterIteratorMediatorMementoAnd a few more …
45
Summary
Main point: to recognize that there are proven solutions to problems that a designer/ programmer may encounterSolutions are results of others’ experiencesTowards “standard approaches”
Search for such solutions firstAlthough there is some merit attempting to
create the solution yourself
Becoming a design architect