Design Patterns

Prototype



Design Pattern Type: Behavioral

GoF Statement of Intent:


Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
Brief Overview:



Prototype is a creation design pattern in which the type of objects to be created are cloned from a prototypical instance to create new objects. A base class is created which contains a virtual clone() function. Subclasses then represent the objects to be created. Calling clone() on one of the base classes creates an instance of the object identical to the prototype which can then be specialized as needed.
UML Diagram:

Discussion and In-class Example:

Take another look at your role playing video game. Suppose you wanted to be able to create new, unique monsters, or even allow the players to create new monsters as the play level rises.

In this diagram the MonsterRegistry creates new monsters. If you have ever played Dungeons and Dragons then you know how a monster is defined by the character traits, etc. Suppose you create a generic Monster interface, but have all the characteristics set at run time by the MonsterRegistry. Now let the MonsterRegistry either have algorithms to randomly generate monsters or let it read the data to define monsters from a data file, or use a combination of both.