Prototype patternYu Chen &Ider ZhengCSE 776 - Design Patterns by Jim FawcettFall 2011
 Who?What? Why? When?How?4W1HY & IStructure/ParticipantsConsequencesApplicabilityImplementation
Intent“Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.”
Real life analogyCopy Machine
Real life analogyCopy MachineProduct PrototypesDie Sinking
structure
structurePrototypeConcreteConcreteClientClone()Clone()Clone()Operation()p = prototype->Clone()Return copy of itselfReturn copy of itself
participantsPrototypeDeclares an instance for cloning itselfConcrete PrototypeImplement an operation of cloning itselfClientCreates an object by asking the prototype to clone itself
consequencesSpecifying new objects by varying values.Specifying new objects by varying structure.Reduced subclassing.Configuring an application with classes dynamically.Adding and removing products at run-time.
applicabilityWhen a system should be independent of how its products are created, composed, and represented.When the classes to instantiate are specified at run-timeTo avoid building a class hierarchy of factories that parallels the class hierarchy of productsWhen instances of a class can have one of only a few different combinations of state.
Implementation issuesImplementing the Clone operation.Binding the concrete prototypes
Copy Constructor VSPrototype Pattern
Shallow CopyVSDeep Copy
Implementation issuesImplementing the Clone operation.Binding the concrete prototypes
structure?PrototypeConcreteConcreteClientClone()Clone()Clone()Operation()p = prototype->Clone()Return copy of itselfReturn copy of itself
FactoriesFactory: private ConcreteA* _prototypeA; // we can have moreFactory: public MakeA() { return _prototypeA->clone(); }Client: Base* obj = MakeA(); Client: obj->MoreActions();
Prototype managersCreate and destroy prototype at run-timeRegister new prototypesUnregister prototypesClient retrieve and store prototype from prototype managerUse map<key,prototype>
CASE STUDY - tetris
Tetris cont.
Tetris cont.
Tetris cont.
Tetris cont.
Tetris Cont.
Tetris cont.
Tetris cont.
Tetris cont.

Prototype Pattern