Transcription

Object-Oriented Design PatternsDavid JanzenEECS 816 Object-Oriented Software DevelopmentUniversity of Kansas

Outline Introduction––––Design Patterns OverviewStrategy as an Early ExampleMotivation for Creating and Using Design PatternsHistory of Design Patterns Gang of Four (GoF) Patterns– Creational Patterns– Structural Patterns– Behavioral PatternsCopyright 2006 by David S.Janzen. All rights reserved.2

What are Design Patterns? In its simplest form, a pattern isa solution to a recurring problemin a given context Patterns are not created, but discovered oridentified Some patterns will be familiar?– If you’ve been designing and programming forlong, you’ve probably seen some of the patternswe will discuss– If you use Java Foundation Classes (Swing),Copyright 2006 by David S.3you have certainlyusedsomedesignpatternsJanzen. All rights reserved.

Design Patterns Definition1 Each pattern is a three-part rule, whichexpresses a relation between– a certain context,– a certain system of forces which occursrepeatedly in that context, and– a certain software configuration which allowsthese forces to resolve themselves1. Dick Gabriel, ght 2006 by David S.Janzen. All rights reserved.4

A Good Pattern1 Solves a problem:– Patterns capture solutions, not just abstractprinciples or strategies. Is a proven concept:– Patterns capture solutions with a track record, nottheories or speculation1. James O. Coplien, ght 2006 by David S.Janzen. All rights reserved.5

A Good Pattern The solution isn't obvious:– Many problem-solving techniques (such assoftware design paradigms or methods) try toderive solutions from first principles. The bestpatterns generate a solution to a problemindirectly--a necessary approach for the mostdifficult problems of design. It describes a relationship:– Patterns don't just describe modules, butdescribe deeper system structures andmechanisms.Copyright 2006 by David S.Janzen. All rights reserved.6

A Good Pattern The pattern has a significant humancomponent (minimize human intervention).– All software serves human comfort or qualityof life; the best patterns explicitly appeal toaesthetics and utility.Copyright 2006 by David S.Janzen. All rights reserved.7

Outline Introduction––––Design Patterns OverviewStrategy as an Early ExampleMotivation for Creating and Using Design PatternsHistory of Design Patterns Gang of Four (GoF) Patterns– Creational Patterns– Structural Patterns– Behavioral PatternsCopyright 2006 by David S.Janzen. All rights reserved.8

Strategy Pattern Intent:– Define a family of algorithms, encapsulate each one, andmake them interchangeable. Strategy lets the algorithm varyindependently from clients that use it. Basic Idea:– Make an algorithm an object so you can switch it– common pattern to replace case statements– client chooses which strategy to use Also Known As Policy Examples– several ways to find line breaks in text (simple, TeX, array) 2006 by David S.9– many ways to ffsJanzen. All rights reserved.

Strategy PatternGeneral StructureClientStrategyContext setConcreteStrategy() creteStrategyC doAlgorithm() doAlgorithm() doAlgorithm()Copyright 2006 by David S.Janzen. All rights reserved.10

Strategy Pattern: Rock, Paper, ScissorsRPSGame RPSGame(aPlayer : RPSChooser*) play() : void- t oS tring( : RPS) : st ring- winner( : RPS, : RPS) : string- t oRPS( : char) : RPS enum RPS ROCK PAPER SCISSORSRPSChooser-compPlayer abstract getChoice() : RPSRotatingRPSChooser- counter : int RotatingRPSChooser() getChoice() : RPSCopyright 2006 by David S.Janzen. All rights reserved.StuckRPSChooser getChoice() : RPS11

Strategy Pattern:Rock, Paper, Scissorsenum RPS {ROCK, PAPER, SCISSORS };class RPSChooser{public:virtual RPS getChoice() 0;};class RotatingRPSChooser : public RPSChooser{public:RotatingRPSChooser() : counter(0) {}RPS getChoice() { return ( counter %3 0)?ROCK:(counter%3 1)?PAPER:SCISSORS; }private:int counter;};class StuckRPSChooser : public RPSChooser{public:RPS getChoice() { returnCopyright SCISSORS; 2006 by David S. }12Janzen. All rights reserved.};

Strategy Pattern:Rock, Paper, Scissorsclass RPSGame{public:RPSGame(RPSChooser* aPlayer) { compPlayer aPlayer; } };void RPSGame::play(){char choice;do {cout "Enter your choice (R)ock, (P)aper, (S)cissor cin choice;if (choice! 'Q'){RPS compChoice compPlayer- getChoice(); }int main() { RPSGame rps(choice 'S'?newRotatingRPSChooser:Copyright 2006by David S.13Janzen.newAll rightsreserved.StuckRPSChooser);

Outline Introduction––––Design Patterns OverviewStrategy as an Early ExampleMotivation for Creating and Using Design PatternsHistory of Design Patterns Gang of Four (GoF) Patterns– Creational Patterns– Structural Patterns– Behavioral PatternsCopyright 2006 by David S.Janzen. All rights reserved.14

Why Patterns? Code Reuse is good– Software developers generally recognize thevalue of reusing code reduces maintenance reduces defect rate (if reusing good code) reduces development time– Code Reuse Pitfalls Reusing code blindly (out of context) Reusing unproven or untested codeCopyright 2006 by David S.Janzen. All rights reserved.15

Why Patterns? Design Reuse is better– Similar benefits and pitfalls to Code Reuse– Identifying reuse early in the developmentprocess can save even more time– Copying proven solutions– Solutions can be analyzed visually with UMLwithout complexities of the codeCopyright 2006 by David S.Janzen. All rights reserved.16

Why Patterns? Good designs reduce dependencies/coupling– Many patterns focus on reducingdependencies/coupling– Strongly coupled code hard to reuse changes have wide effects– Loosely coupled code objects can be reused 2006by David S. changes haveCopyrightisolatedeffectsJanzen. All rights reserved.17

Why Patterns?1 Common vocabulary and language– Fundamental to any science or engineeringdiscipline is a common vocabulary forexpressing its concepts, and a language forrelating them together.– Patterns help create a shared language forcommunicating insight and experience aboutrecurring problems and their solutions.1. http://hillside.net/patternsCopyright 2006 by David S.Janzen. All rights reserved.18

Why Patterns? Common vocabulary and language– Sunday’s Game Analogy: Call an option left from the line when in the Pro Setformation and the defense shows blitz. Pattern Name: Option on Blitz Context: Offense in Pro Set-formation, Defense showsBlitzCopyright 2006 by David S.Janzen. All rights reserved.19

Outline Introduction––––Design Patterns OverviewStrategy as an Early ExampleMotivation for Creating and Using Design PatternsHistory of Design Patterns Gang of Four (GoF) Patterns– Creational Patterns– Structural Patterns– Behavioral PatternsCopyright 2006 by David S.Janzen. All rights reserved.20

Design Patterns History Christopher Alexander (architect)“A Pattern Language”, 1977– quality architectural designs can be described reused objectively agreed to be good– structures solve problems– multiple structures can solve the same problem– similarities in these structures can form a pattern* see www.greatbuildings.com/architects/Christopher Alexander.htmland ht 2006 by David S.Janzen. All rights reserved.21

Design Patterns History ESPRIT consortium in late 1980’s developeda pattern-based design methodology inspiredby Alexander’s work OOPSLA’87 Kent Beck and WardCunningham introduced idea of identifyingpatterns in software engineering– http://c2.com/cgi/wiki?WardAndKent– Well known for work in Smalltalk, CRC Cards,xUnit testing framework, eXtreme Programming,Copyright 2006 by David S.22.Janzen. All rights reserved.

Design Patterns Resources “Design Patterns: Elements of Reusable ObjectOriented Software”– by Gamma, Helm, Johnson, and Vlissides– Gang of Four (GoF)– 1994 Software Productivity Award “Java Design Patterns” by James Cooper– Some examples used in presentation http://hillside.net/patterns/patterns.html http://patterndigest.com http://wiki.cs.uiuc.edu/PatternStories/Copyright 2006 by David S.Janzen. All rights reserved.23

Design Patterns GoF grouped patterns into three areas:– Creational Patterns Abstract Factory, Builder, Factory Method,Prototype, Singleton– Structural Patterns Adapter, Bridge, Composite, Decorator, Façade,Flyweight, Proxy– Behavioral Patterns Chain of Responsibility, Command, Interpreter,Iterator, Mediator, Memento, Observer, State,Strategy, TemplateCopyright Method,2006 by DavidVisitorS.Janzen. All rights reserved.24

Design Patterns GoF book preceded commercial release of Java Java language designers read GoF Hence Java libraries implement many GoFDesign Patterns––––Iterator on Vector or ArrayListObserver (interface) and Observable (class)WindowAdapterStack Similarly, C STL implements many patternsCopyright 2006 by David S.Janzen. All rights reserved.25

Outline Introduction––––Design Patterns OverviewStrategy as an Early ExampleMotivation for Creating and Using Design PatternsHistory of Design Patterns Gang of Four (GoF) Patterns– Creational Patterns– Structural Patterns– Behavioral PatternsCopyright 2006 by David S.Janzen. All rights reserved.26

Creational Patterns Better ways to create an instance Abstract the instantiation process– hide how class instances are created and combined– Traditional creation: MyType t new MyType();– client code is now dependent on MyType– changing MyType means changing all clients– clients must know of different ways to create MyType» (e.g. constructor parameters) GoF Creational Patterns– Factory Method– Simple Factory, Abstract FactoryCopyright 2006 by David S.– Builder, Prototype,SingletonJanzen. All rights reserved.27

Intent:Factory Method– Define an interface for creating an object, but letsubclasses decide which class to instantiate. FactoryMethod lets a class defer instantiation to subclasses. Also Known As: Virtual Constructor Basic Idea:– a client creates a product through an abstract class– i.e. a concrete subclass knows how to create theproduct, the client only knows the parent abstract classand the factory method to call to get the productCopyright 2006 by David S.Janzen. All rights reserved.28

Factory MethodGeneral StructureClientCreatorProduct AnOperation() FactoryMethod() doSomething()ConcreteProductBConcreteProductA doSomething() doSomething()ConcreteCreatorAConcreteCreatorB FactoryMethod() FactoryMethod()Copyright 2006 by David S.Janzen. All rights reserved.29

Factory MethodGeneral Behavior: Client1:: ConcreteCreatorB2: FactoryMethod()3:: ConcreteProductB4: return5: doSomething()Copyright 2006 by David S.Janzen. All rights reserved.30

GoF Maze prior to PatternsMazeGameMaze-Rooms : Room[] CreateMaze() : Maze* AddRoom() : void RoomNo() : void enumeration DirectionNorthSouthEastWestMapSite Enter() : voidWallRoom-roomNumber : int-sides : MapSite* [4]Door-isOpen : boolean GetSide( direction : Direction ) : MapSite* constructor Room( roomNum : int ) SetSide( direction : Direction, site : MapSite ) : void constructor Door( room1 : Room*, room2 : Room* ) OtherSideFrom( room : Room* ) : Room*Copyright 2006 by David S.Janzen. All rights reserved.31

GoF Maze prior to PatternsMaze* MazeGame::CreateMaze( ){Maze* aMaze new Maze;Room* r1 new Room(1);Room* r2 new Room(2);Door* theDoor new Door(r1, r2);aMaze- AddRoom(r1);aMaze- AddRoom(r2);//Client codeint main(){MazeGame* mg;mg new MazeGame();Maze* m mg.CreateMaze();//do something with m}r1- SetSide(North, new Wall);r1- SetSide(East, theDoor);r1- SetSide(South, new Wall);r1- SetSide(West, new Wall);r2- SetSide(North, new Wall);r2- SetSide(East, new Wall);r2- SetSide(South, new Wall);r2- SetSide(West, theDoor);return aMaze;Copyright 2006 by David S.}Janzen. All rights reserved.32

Problems with GoF MazeMaze* MazeGame::CreateMaze( ){Client hard-codes callsMaze* aMaze new Maze;to constructors.Room* r1 new Room(1);Room* r2 new Room(2);Door* theDoor new Door(r1, r2); What if we want to putbombs in rooms thatcan destroy walls, ormake an enchantedmaze where doors mayhave spells and roomsmay contain spells andmagic keys?aMaze- AddRoom(r1);aMaze- AddRoom(r2);r1- SetSide(North, new Wall);r1- SetSide(East, theDoor);r1- SetSide(South, new Wall);r1- SetSide(West, new Wall);r2- SetSide(North, new Wall);r2- SetSide(East, new Wall);r2- SetSide(South, new Wall);How would we reuser2- SetSide(West, theDoor);and extend this code?return aMaze;Copyright 2006 by David S.33}Janzen. All rights reserved.

Problems with GoF MazeMaze* MazeGame::CreateMaze(char mazeType){Bad Approach: usesMaze* aMaze new Maze;multiple if/then/else.switch(mazeType) {case ‘N’ : Room* r1 new Room(1);Room* r2 new Room(2); break;case ‘B’ : Room* r1 new RoomWithABomb(1);Room* r2 new RoomWithABomb(2);break;case ‘E’ :Room* r1 new EnchantedRoom(1,CastSpell());Room* r2 new EnchantedRoom(2,CastSpell()); break;}if (mazeType ‘E’)Door* theDoor new DoorNeedingSpell(r1, r2);elseDoor* theDoor new Door(r1, r2); Copyright 2006 by David S.Janzen. All rights reserved.34

GoF Maze with Factory MethodMazeGameMaze-Rooms : Room[] AddRoom() : void RoomNo() : void CreateMaze() : Maze* MakeDoor() : Door* MakeMaze() : Maze* MakeRoom() : Room* MakeWall() : Wall*MapSiteFactory Methods Enter() : voidRoom-roomNumber : int-sides : MapSite* [4]WallDoor-isOpen : boolean constructor Door( room1 : Room*, room2 : Room* ) OtherSideFrom( room : Room* ) : Room* GetSide( direction : Direction ) : MapSite* constructor Room( roomNum : int ) SetSide( direction : Direction, site : MapSite ) : Copyrightvoid 2006 by David S.Janzen. All rights reserved.35

GoF Maze with Factory MethodsMaze* MazeGame::CreateMaze( ){Client calls Factory Methods.Maze* aMaze MakeMaze();Room* r1 MakeRoom(1);Room* r2 MakeRoom(2);Door* theDoor MakeDoor(r1, r2);virtual Maze* MakeMaze()aMaze- AddRoom(r1);aMaze- AddRoom(r2);{return new Maze; }virtual Wall* MakeWall()r1- SetSide(North, MakeWall());{ return new Wall; }r1- SetSide(East, theDoor);r1- SetSide(South, MakeWall());r1- SetSide(West, MakeWall());r2- SetSide(North, MakeWall());Now we can inheritr2- SetSide(East, MakeWall());from MazeGame andr2- SetSide(South, MakeWall());specialize parts of ther2- SetSide(West, theDoor);return aMaze;Copyright 2006 by David S. maze.36}Janzen. All rights reserved.

Extending FactoryMethod GoF MazeMazeGameMaze CreateMaze() : Maze* MakeDoor() : Door* MakeMaze() : Maze* MakeRoom() : Room* MakeWall() : Wall*-Rooms : Room[] AddRoom() : void RoomNo() : voidBombedMazeGameEnchantedMazeGame MakeRoom() : Room* MakeWall() : Wall*#CastSpell() : Spell* MakeDoor( r1 : Room*, r2 : Room* ) : Door* MakeRoom( n : int ) : Room*MapSite Enter() : voidWallRoomDoor-isOpen : boolean-roomNumber : int-sides : MapSite* [4] GetSide( direction : Direction ) : MapSite* constructor Room( roomNum : int ) SetSide( direction : Direction, site : MapSite ) : void constructor Door( room1 : Room*, room2 : Room* ) OtherSideFrom( room : Room* ) : ngSpellCopyright 2006 by David S.Janzen. All rights reserved.37

Extending Factory Method GoF Mazeclass BombedMazeGame : public MazeGame {public:BombedMazeGame();virtual Wall* MakeWall() const{ return new BombedWall; }virtual Room* MakeRoom(int n) const{ return new RoomWithABomb(n); }};//Client codeint main(){MazeGame* mg;mg new BombedMazeGame();Maze* m mg.CreateMaze();//do something with m}Copyright 2006 by David S.Janzen. All rights reserved.Only one linechanges in client.38

Extending Factory Method GoF Mazeclass EnchantedMazeGame : public MazeGame {public:EnchantedMazeGame();virtual Room* MakeRoom(int n) const{ return new EnchantedRoom(n, CastSpell()); }virtual Door* MakeDoor(Room* r1, Room* r2) const{ return new DoorNeedingSpell(r1,r2); }protected:Spell* CastSpell() const;};//Client codeint main(){MazeGame* mg;mg new EnchantedMazeGame();Maze* m mg.CreateMaze();//do something with m}Copyright 2006 by David S.Janzen. All rights reserved.Only one linechanges in client.39

(Simple) Factory PatternGeneral StructureProduct doSomething()ProductA doSomething()ProductB doSomething()ClientConcreteFactory getProduct()Copyright 2006 by David S.Janzen. All rights reserved.40

(Simple) Factory PatternGeneral Behavior: Client1:: ConcreteFactory2: getProduct()3:: ProductB4: return5: doSomething()Copyright 2006 by David S.Janzen. All rights reserved.41

Abstract Factory Pattern Intent:– Provide an interface for creating families of relatedor dependent objects without specifying theirconcrete classes. Also Known As: Kit Basic Idea:– a client object refers to a family of related objectsusing only abstract classesCopyright 2006 by David S.Janzen. All rights reserved.42

Abstract Factory Vehicle Rentals Suppose we have a system for making rentalcar reservationsWebClient MakeReservation()VehicleInventoryReservation Reservation() getAvailVehicle(numPassengers : Integer)PrimaryDriverCopyright 2006 by David S.Janzen. All rights reserved.Vehicle43

Abstract Factory Hotel Rentals Now suppose we want to make reservationsfor not only rental cars, but also hotelsWebClient MakeReservation()Reservation Reservation()Property getAvailRoom(numGues ts : Int eger) : RoomRoomPrimaryGuest getName()getAddress()getNumGuests() : IntegerPrimaryGuest(name : String, address : String, guests : Integer) getRoomNum() : Integer Room(num : Integer, capacity : Integer) getCapacity() : Integer– Looks familiar,huh?Copyright 2006 by David S.Janzen. All rights reserved.44

Abstract Factory Pattern We want to create families of reservations WebClient can be independent of the kind of reservationWebClientReservation AbstractFactory1 createProductUnit() : Unit createProductCustomer() : Customer createProductUnitInventory() : UnitInventory rvationFactoryUnitCustom er Customer(name : String, numGuests : Integer) getName() : String getNumCustomers() : IntegerPrimaryGuestPrimaryDriverUnitInventory Unit(id : Integer, capacity : Integer) getUnitNum() : Integer getCapacity() : IntegerRoomVehicleCopyright 2006 by David S.Janzen. All rights reserved. getAvailUnit() : UnitPropertyVehicleInventory45

Abstract Factory Pattern Exercise We can even add a ReservationFactoryChooserwhich is a Factory Method that pulls the Factorychoice out of WebClientWebClientReservation AbstractFactory MakeReservation() createProductUnit() : Unit createProductCus tomer() : Customer createProductUnitInventory() : UnitInventoryReservationFactoryChooser getReservationFactory () : Reservat ion AbstractFactoryRoomReservationFactory Customer(name : String, numGuests : Integer) getName() : String getNumCustomers() : ustom er Unit(id : Integer, capacity : Integer) getUnitNum() : Integer getCapacity() : ht 2006 by David S.Janzen. All rights reserved. getAvailUnit() : UnitPropertyVehicleInventory46

Abstract Factory PatternGeneral StructureClientAbstractFactory CreateProductA() CreateProductB()ConcreteFactory1ConcreteFactory2 CreateProductA() CreateProductB() CreateProductA() opyright 2006 by David S.Janzen. All rights reserved.ConcreteProductA247

Abstract Factory PatternGeneral Behavior: Client1:: ConcreteFactory22: CreateProductA()3:: ConcreteProductA24: return5: doSomething()6: CreateProductB()7:: ConcreteProductB28: returnCopyright 2006 by David S.Janzen. All rights reserved.48

Factory Pattern Differences Simple Factory– client asks a concrete factory class for a concreteobject that will do what client wants– factory only returns one product When to use– when factory only returns one product one product may have multiple variations all withperhaps some common functionalityCopyright 2006 by David S.Janzen. All rights reserved.49

Factory Pattern Differences Factory Method– client instantiates a concrete factory class (childof a common abstract class) and invokes amethod on it that selects a concrete product class When to use– when client can’t anticipate the class of objects itmust create– factory wants concrete factories to decide whatconcrete product to useCopyright 2006 by David S.Janzen. All rights reserved.50

Factory Pattern Differences Abstract Factory– client creates a concrete factory class that canproduce several concrete products– client only references abstract factory andabstract products When to use– when client needs a family of products, but wantsto be independent of themCopyright 2006 by David S.Janzen. All rights reserved.51

Singleton Pattern Intent:– Ensure a class only has one instance, and providea global point of access to it Singleton should be considered only if allthree of the following criteria are satisfied:– Ownership of the single instance cannot bereasonably assigned to some other class– Lazy initialization is desirable– Global access is not otherwise provided forCopyright 2006 by David S.Janzen. All rights reserved.52

Singleton Implementation Options Many technical issues dealing with inheritance,multithreading and destruction Java– final class with static methods– class with a static variable, static method, and privateconstructor– class with a static variable and public constructor thatthrows an exception on subsequent calls C – Static method, non-public constructor– Non-public copy constructor– Return reference instead of pointer so can’t be deletedCopyright 2006 by David S.Janzen. All rights reserved.53

Singleton PatternExample: Print Spoolerpublic class PrintSpooler {//a prototype for a spooler class//such that only one instance can ever existprivate static PrintSpooler spooler;private PrintSpooler() {//privatized}public static synchronized PrintSpooler getSpooler() {if (spooler null)spooler new PrintSpooler();return spooler;//always returns the spooler}public void print(String s) {System.out.println(s);}}Copyright 2006 by David S.Janzen. All rights reserved.54

Singleton PatternGeneral Structure: static method, staticmember, private constructorPrintSpooler getSpooler() : PrintSpooler print( s : String ) : void-PrintSpooler()Copyright 2006 by David S.Janzen. All rights reserved.-spooler55

Singleton PatternExample: Print Spoolerpublic class Spooler {//this is a prototype for a printer-spooler class//such that only one instance can ever existstatic boolean instance flag false; //true if//one instancepublic Spooler() throws SingletonException{if (instance flag)throw new SingletonException("Only one printer allowed");elseinstance flag true;//set flag for one instanceSystem.out.println("printer opened");}}Copyright 2006 by David S.Janzen. All rights reserved.56

Singleton PatternGeneral Structure: static member, publicconstructor, throws exceptionSpoolerSingletonException SingletonException() SingletonException( s : String ) instance flag : boolean false Spooler()Copyright 2006 by David S.Janzen. All rights reserved.57

Intent :Builder Pattern– Separate the construction of a complex objectfrom its representation so that the sameconstruction process can create differentrepresentations Basic Idea:– Create a separate class that constructs each ofseveral complex objects. That way theconstruction process is separate from itsrepresentation and it can produce differentrepresentations.Copyright 2006 by David S.Janzen. All rights reserved.58

Builder PatternClientDirectorBuilder BuildPart()ConcreteBuilderProduct BuildPart() GetProduct()Copyright 2006 by David S.Janzen. All rights reserved.59

Builder Pattern: Client1:2:: ConcreteBuilder: Director3:4: BuildPart()5: GetProduct()Copyright 2006 by David S.Janzen. All rights reserved.60

Builder Pattern:Benefits Isolates code for construction andrepresentation– ConcreteBuilder’s can be reused by multipleDirectors Lets you vary a product’s internalrepresentation– Construction process is hidden from clients Gives you finer control over the constructionprocess– Good for multi-step construction processesCopyright 2006 by David S.Janzen. All rights reserved.61

Builder Pattern:When to Use When the algorithm for creating a complexobject should be independent of the parts thatmake up the object and how they’reassembled When the construction process must allowdifferent representations for the object that isconstructedCopyright 2006 by David S.Janzen. All rights reserved.62

Prototype Pattern Intent:– Specify the kinds of objects to create using aprototypical instance, and create new objects bycopying this prototype. Example:– Music score editor clones typical objects such asstaff, note, rest, Similar benefits to Abstract Factory and Builder– Hides concrete product classes from client Basic Idea:– Create an objectthat you will copy (clone) and63Copyright 2006 by David S.Janzen. All rights reserved.modify as needed

Prototype PatternClientPrototype Clone()ConcretePrototypeAConcretePrototypeB Clone() Clone()Copyright 2006 by David S.Janzen. All rights reserved.64

Prototype Pattern:Benefits Alternative to Abstract Factory and Builder Can allow products to be added and removedat run-time May reduce subclassing– Don’t need all the creator classes needed inFactory Method May be able to create new objects– by varying the values given to the prototype– Or by varying the objects composing theprototypeCopyright 2006 by David S.Janzen. All rights reserved.65

Prototype Pattern:When to Use When you want to decouple a client from theproducts that it creates When the classes to instantiate are specifiedat run-time When instances of a class can have one ofonly a few different combinations of stateCopyright 2006 by David S.Janzen. All rights reserved.66

A Creational Patterns MetaphorMemory Aid Simple Factory:Trabant– East German car with a 7-year wait, one modeldepending on year of delivery, factory determineswhich model is given depending on which year yourTrabant is delivered Factory Method:Honda– Client asks an AccordFactory or a CivicFactory tomake an Accord or a CivicCopyright 2006 by David S.Janzen. All rights reserved.67

A Creational Patterns MetaphorMemory Aid Abstract Factory:General Motors– client asks for a PontiacFactory to create aGrandPrix and a TransAm– client asks for a GMCFactory to create a half-tonpickup and a Yukon Builder:Kit Car– client gives director a Kit Car kit and asks it tocreate a kit car for itCopyright 2006 by David S.Janzen. All rights reserved.68

A Creational Patterns MetaphorMemory Aid Singleton:Uncle Randy’s Dune Buggy– create a one-of-a-kind vehicle from scratch Prototype:Copy my favorite car– make a copy of my favorite car so I can drive theoriginal until it is worn out, and still have anotherone to enjoy when I’m done with the firstCopyright 2006 by David S.Janzen. All rights reserved.69

Outline Introduction––––Design Patterns OverviewStrategy as an Early ExampleMotivation for Creating and Using Design PatternsHistory of Design Patterns Gang of Four (GoF) Patterns– Creational Patterns– Structural Patterns– Behavioral PatternsCopyright 2006 by David S.Janzen. All rights reserved.70

Structural Patterns Ways to combine classes and objects intolarger structures Structural Class Patterns use inheritance tocompose interfaces or implementations– Multiple Inheritance, Adapter Structural Object Patterns compose objectsto realize new functionality– Adapter, Bridge, Composite, Decorator, Façade,Flyweight, ProxyCopyright 2006 by David S.Janzen. All rights reserved.71

Adapter Pattern Intent:– Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn’t otherwise because ofincompatible interfaces. Basic Idea:– Create a new class that provides a new interface for an existing class. Two types:– class adapter uses inheritance– object adapter uses composition Also known as Wrapper Silly Example:– Coffee server responds to regular or decaf– Client wants to say regular or unleadedCopyright 2006 by David S.Janzen. All rights reserved.72

Adapter Pattern Example Suppose you have written a large application thatuses a queue and calls enqueue and dequeue toinsert and remove items from the queueclass Queue {public:Queue() : length(0) {}void enqueue(Item i) { q[length ] i; }Item dequeue() { Item tmp q[0];for(int i 0;i length;i )q[i] q[i 1];length--;return tmp;}private:Item q[100];int length;};Copyright 2006 by David S.Janzen. All rights reserved.73

Adapter Pattern Exampleint main() {Queue requests;Item request;char choice;do{cout "Do you want to (E)nter or (R)etrieve a request?cin choice;if (choice 'E'){cout "Enter your one character request" endl;cin request;requests.enqueue(request);}else if (choice 'R')cout "The next request is " requests.dequeue()} while(choice ! 'Q');//many more calls to enqueue and dequeue.Copyright 2006 by David S.Janzen. All rights reserved.74

Adapter Pattern Example Now you discover that the STL contains aqueue class that is more efficient than yours– The only problem is that the STL queue usespush and pop instead of enqueue and dequeue– What are your choices? Replace all calls to enqueue and dequeue with pushand pop respectively– No, you have A LOT of code to change Define an adapter that makes the S

– Sunday’s Game Analogy: Call an option left from the line when in the Pro Set-formation and the defense shows blitz. Pattern Name: Option on Blitz . – Motivation for Creating and Using Design Patterns – History of Design Patterns Gang of Four (GoF) Patterns – Creational