Prototype Design Pattern
Category : Design Patterns
| Sub Category : Creational design patterns | By Prasad Bonam Last updated: 2023-07-09 12:56:42
Viewed : 66
Prototype Design Pattern:
The Prototype pattern is a creational design pattern that allows cloning or copying objects without coupling the client code to their specific classes. It involves creating a prototype object and then creating new instances by copying or cloning the prototype. This pattern helps avoid the overhead of creating objects from scratch and provides a way to create new objects with customizable initial states. Here is an example of implementing the Prototype pattern in Java:
In this example:
Prototype interface declares the
clone() method, which allows creating a new instance of the object by cloning the prototype.
ConcretePrototype class implements the
Prototype interface and provides the concrete implementation of the
clone() method. It also has a copy constructor that allows creating a new instance with the same state as an existing object.
Client class demonstrates how to use the prototype by creating a prototype object and cloning it to create multiple instances.
- In the
main() method, a
ConcretePrototype instance is created as a prototype. Then, two clones of the prototype are created using the
clone() method, and their names are printed.
By using the Prototype pattern, you can create new instances of objects by cloning a prototype instead of instantiating them from scratch. This approach allows you to customize the initial state of the cloned objects while maintaining the decoupling between the client code and specific classes.