- Create a new Object
- Copy the Object.
How to Implement Prototype Pattern?
Prototype Design Pattern is basically use to copy objects, and here we have to implement Cloneable interface so that with clone method we can have clone of object, Below is the example by which it can be more clear about it.
Here check the code written in red which is mandatory to implement Prototype design pattern.
Applicability & Examples
Use Prototype Pattern when a system should be independent of how its products are created, composed, and represented, and:
- Classes to be instantiated are specified at run-time.
- Avoiding the creation of a factory hierarchy is needed.
- It is more convenient to copy an existing instance than to create a new one.
In building stages for a game that uses a maze and different visual objects that the character encounters it is needed a quick method of generating the haze map using the same objects: wall, door, passage, room… The Prototype pattern is useful in this case because instead of hard coding (using new operation) the room, door, passage and wall objects that get instantiated, CreateMaze method will be parameterized by various prototypical room, door, wall and passage objects, so the composition of the map can be easily changed by replacing the prototypical objects with different ones.
Suppose we are doing a sales analysis on a set of data from a database. Normally, we would copy the information from the database, encapsulate it into an object and do the analysis. But if another analysis is needed on the same set of data, reading the database again and creating a new object is not the best idea. If we are using the Prototype pattern then the object used in the first analysis will be cloned and used for the other analysis.
If you like reading please spare 5 seconds to share this else you can comment and provide feedback to improve it.