Prototype
Contents |
Structure
The Prototype class declares the clone() method, which is implemented by all subclasses as a way to return a copy of itself. The Client class creates a new object by telling the Prototype class to clone itself.
Usage
The Prototype pattern should be used:
- When a system needs to be independent of how it's products are created, composed and represented.
- When the classes to instantiate are specified at run time
- To avoid building parallel hierarchies of factories and products.
- When an instance of a class can be only one of a few different states. The Prototype pattern may be more convenient than instantiating the class manually each time with the appropriate state.
Example
A good example for this pattern is given in the Gang of Four Design Patterns book. They describe a music score editor, which is built by adding music objects such as Notes and Staves to a graphical editor framework. The graphical editor also has Tools for manipulating Graphic objects, such as selecting, moving etc. There must also be a way to create Graphic objects and add them to the editor, which they call GraphicTool which is a subclass of Tool. The example diagram from the book is below:
The GraphicTool class creates a problem. It is part of the graphical editor framework, and doesn't know how to create music objects such as Notes and Staves etc. One solution would be to create sublcasses of GraphicTool for each music object that we need to create, however these subclasses would only differ in the type of music object that they create. This would also create the Parallel hierarchies problem.
The solution is to make the GraphicTool create a new Graphic by "cloning" an instance of a subclass of Graphic. This cloned instance is called a prototype. Each GraphicTool object is initialized with the prototype that it is designated to create. Each GraphicTool instance will add it's music object to the score by cloning it's prototype and adding the clone to the score. The GraphicTool class can clone any type of Graphic as long as all Graphic subclasses support the clone() method.