Prototype Design Pattern

/Prototype Design Pattern

Introduction

Prototype allows us to hide the complexity of making new instances from the client. The concept is to copy an existing object rather than creating a new instance from scratch, something that may include costly operations. The existing object acts as a prototype and contains the state of the object. The newly copied object may change same properties only if required. This approach saves costly resources and time, especially when the object creation is a heavy process. It allows an object to create customized objects without knowing their class or any details of how to create them.

Intent

  • Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • Co-opt one instance of a class for use as a breeder of all future instances.

 

Implementation

The classes participating to the Prototype Pattern are:

  • Client – Creates a new object by asking a prototype to clone itself.
  • Prototype – Declares an interface for cloning itself.
  • ConcretePrototype – Implements the operation for cloning itself.

 

Example

public interface Prototype {
  public abstract Object clone ( );
}

public class ConcretePrototype implements Prototype {
  public Object clone() {
    return super.clone();
  }
}

public class Client {

  public static void main( String arg[] ) 
  {
    ConcretePrototype obj1 = new ConcretePrototype ();
    ConcretePrototype obj2 = obj1.clone();
  }
}

 

September 8th, 2019|Categories: Uncategorized|Tags: |
avatar
  Subscribe  
Notify of