Prototype Design Pattern

Category : Design Patterns | Sub Category : Creational design patterns | By Prasad Bonam Last updated: 2023-07-09 07:26:42 Viewed : 303


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:

java
// Prototype interface
// Prototype interface public interface Prototype { Prototype clone(); } // Concrete prototype class public class ConcretePrototype implements Prototype { private String name; public ConcretePrototype(String name) { this.name = name; } // Copy constructor public ConcretePrototype(ConcretePrototype prototype) { this.name = prototype.name; } @Override public Prototype clone() { return new ConcretePrototype(this); } public String getName() { return name; } } // Client code public class Client { public static void main(String[] args) { ConcretePrototype prototype = new ConcretePrototype("Prototype"); ConcretePrototype clone1 = (ConcretePrototype) prototype.clone(); System.out.println("Clone 1: " + clone1.getName()); // Output: Clone 1: Prototype ConcretePrototype clone2 = (ConcretePrototype) prototype.clone(); System.out.println("Clone 2: " + clone2.getName()); // Output: Clone 2: Prototype } }

In this example:

  • The Prototype interface declares the clone() method, which allows creating a new instance of the object by cloning the prototype.
  • The 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.
  • The 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.


Search
Related Articles

Leave a Comment: