Prototype design pattern is used to create an object by cloning a prototype.
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
So the intent is to create an object by using prototype.
Framework needs to instantiate application specific objects.
That means we have a class in framework which wants to create application specific objects but does not know how to create and
get those objects.
Application can use the cloning of instance for subclasses.
We can have a prototype instance which is used to get abstract behavior of Prototype and clone the objects of subclasses.
Where it is applicable?
Framework to be used by developer
To avoid parallel hierarchies.
Wherever it is good to have a prototype and clone it, instead of creating a new object every time.
Prototype class has abstract method Clone(). It provides interface for cloning the object.
ConcretePrototype classes are derived from Prototype and implements the Clone() method. These classes clone
their respective object and returns it to client.
Client has the prototype instance and uses its interface for cloning.
How they work together?
Client has instance of Prototype. It uses the Clone() method of Prototype to clone itself.
It is hiding internal information of product. We can have products added or removed at run time by having prototype
instance whenever required. Reduces subclasses by avoiding parallel hierarchies. You can have prototype instance as part
of another object.
It requires Clone() method in every prototype class. It may be difficult to add in existing classes. Also sometime it
will be difficult when object does not support copy and has circular reference.
We can have Prototype Manager which will manage all the prototypes that includes registering and removing. Client can
just use Prototype Manager with well-defined access.
Cloning has to be taken care appropriately like in case of circular reference. We should be able to make difference
for the use of shallow or deep copy for different scenario. Also there may be requirement for having state of objects
which may require separate method for initialization.
Prototype is very useful pattern and generally used with other patterns too.
Suresh Kumar Srivastava is founder of online learning site coursegalaxy.com and author of popular books "C In Depth",
"Data Structures Through C In Depth". He has 18+ years experience in industry and worked on architecture and design of
multiple products. This article is from his courses on Design Patterns.
CourseGalaxy is focused on transformation of Engineering graduate to Software Engineer to fill the gap
between education and industry and provide the training on specific problems of industry to enhance the skills
of Engineers in industry to do their job appropriately.