Card 02/ 08

ConceptDifficulty: Intermediate1 min

Prototype Pattern Structure: The Class Diagram

A Prototype interface with clone(), and concrete prototypes that copy themselves.

Prototype has three participants: the prototype interface, which declares clone, the concrete prototypes that implement it by copying themselves, and the client that asks for copies. This card reads each role off the Gang of Four's class diagram, and adds the registry of named prototypes that most uses of the pattern include.

Prototype participants
Each participant and its role
ParticipantRole
PrototypeDeclares clone(), which returns a new object of the same kind.
ConcretePrototypeImplements clone() by copying its own fields, and decides how deep that copy goes.
ClientHolds a prototype and calls clone() when it needs a new object, without naming a concrete class.
Prototype registryOptional. A dictionary of prototypes by name, so the client can ask for a copy of the goblin or the goblin-chief.

The diagram is small because the pattern's work happens inside clone(). The client's only arrow points at the interface, so the client can copy an object of any concrete class it is handed. Compare Factory Method and Abstract Factory, where the class to create is fixed by a subclass or a factory: here the object to copy can be chosen at run time, from data.

The registry turns that into a catalogue. At start-up the program configures one object of each kind and registers it under a name. From then on, creating an object means looking up a name and calling clone(), and adding a kind means registering one more configured object, with no new class.