Prototype Design Pattern
This is my third article in Design patterns. In this article, we are going to talk about the Prototype design patterns. When you want to create an object you can use the Factory design pattern. In this design pattern, we don’t create new Objects instead of that clone an existing object instead of creating a new one and can also be customized as per the requirement.
Prototype Design Pattern can be used when the implementation is creating a costly object (Object creation takes more time) or getting more resources this design pattern can use.
As an example, the object creation is done with help of a database because if you want to load some initial values those initial values are coming from the database it takes sometimes. Think if you want to go for the second object why we want to create a new object we can fetch the data from the first object to the second object so that we can be called that clone the object (create a copy of the object).
There are two types of cloning they are deep cloning and shallow cloning.
Advantage of using a prototype design pattern
- We can add or remove the implementation while running: The client can install or uninstall the prototype while running the application.
- Reduced subclassing — Factory Method often produces a hierarchy of Creator classes that parallels the product class hierarchy. The Prototype pattern lets you clone a prototype instead of asking a factory method to make a new object.
- Specifying new objects by varying structure
- Specifying new objects by varying values — Highly dynamic systems let you define new behaviour through object composition by specifying values for an object’s variables and not by defining new classes.
Disadvantages of Prototype Design Pattern
- Overkill for a project that uses very few objects and/or does not have an underlying emphasis on the extension of prototype chains.
- It also hides concrete product classes from the client.
- Each subclass of Prototype must implement the clone () operation which may be difficult when the classes under consideration already exist. Also implementing clone () can be difficult when their internals includes objects that don’t support copying or have circular references.