Pattern: Prototype

Synopsis

This pattern creates an original instance to act as a model for a type of object and copies itself, the instance, to form new objects.

Context

Suppose you have a group of objects to create dynamically that descend from the same common ancestor.  The prototype class will create a prototype instance descended from the common ancestor.   When it is time to create on of the objects dynamically, you copy or clone the object from the prototype and modify it.

 

Forces

The Prototype pattern is a creator pattern.  It is used for creating objects.  If there are objects you want created without knowing the how to create the objects.  If you have objects that need to be created dynamically at runtime and the creation complexity and time of each instance is large.  Also, it can be used to remove subclasses.  If you have multiple subclasses only differ in the objects they create, you could instead clone a prototype of them.


Solution

·        Declare an abstract class with a virtual clone method.

·        The class derives itself from the abstract class, registers its instance, and implements the clone method.

·        The client instead of creating a hardwired class name calls clone on the abstract class indicating which concrete derived class to clone.

This diagram is from javacoder.net.

Image:PrototypeJavacoder.png

Consequences

·        Creates objects with high creation complexity easily.

·        Low on sub-classing.

·        High on initialization.

Implementation

Related Patterns

Abstract Factory, Factory


Modified: 05-Mar-2004
Ted Goodwin