I call this pattern the Dolly pattern. I am not sure if you remember, Dolly was the first sheep to be cloned at least in the news. The key to solving the problem of creating objects which is very expensive from resource point of view, is cloning.
This pattern is based on that only. So by now, you would have guessed how this pattern is different from the other Creational patterns. This pattern doesn’t create them, rather it clones.
So next question is when do we use this pattern. Below are some answers to that.
- If the cost of creating the object is expensive or complicated
- Minimizing the number of classes for an application
- Runtime addition and deletion of objects is required
- Similar new objects are required
Below is how a typical prototype pattern is organized.
Now is raining here @ Seoul, so lets see an example to that itself.
I have created the base prototype as “Day” and then two concrete prototypes as “RainyDay” and “Sunnyday”.
Base Prototype defines 3 plain attributes – Id, weatherType, temperature and accordingly getters and setters for the same. For the ease of having a simple example, I have defined an abstract method for setting the object properties in base prototype “setDefault” which will be set by individual days.
The key points or method in the base prototype to note are:
1. It implements “Cloneable” interface.
2. It overrides “clone” method.
Below is a snippet from the same:
RainyDay and SunnyDay just extends the “Day” and then overrides the “setDefault” to set default values.
Now in effective Prototype pattern, there is concept which is called “caching of objects”. To avoid creating unnecessary objects. Hence I created a new class – “DayCache” which stores already the objects to be created in their basic states.
Once you are done with this setup, you just need to have the client use the Day cache and get the objects or create new via the same technique.
Sample Client invocation:
Hope you like the explanation and the concept!