Creational Patterns - Prototype Pattern

The prototype means making a clone. This implies cloning of an object to avoid creation. If the cost of creating a new object is large and creation is resource intensive, we clone the object. We use the interface Cloneable and call its method clone() to clone the object.

Again letís try and understand this with the help of a non-software example. I am stressing on general examples throughout this write-up because I find them easy to understand and easy to accept as we all read and see them in day-to-day activity. The example here we will take will be of a plant cell. This example is a bit different from the actual cloning in a way that cloning involves making a copy of the original one. Here, we break the cell in two and make two copies and the original one does not exist. But, this example will serve the purpose. Letís say the Mitotic Cell Division in plant cells.
Letís take a class PlantCell having a method split(). The plant cell will implement the interface Cloneable.

Following is the sample code for class PlantCell.

package creational.builder;

* Shows the Mitotic cell division in the plant cell.
public class PlantCell implements Cloneable {

  public Object split() {
    try {
      return super.clone();
}catch(Exception e) {
System.out.println("Exception occured: "+e.getMessage());
return null;
}// End of class

Now letís see, how this split method works for PlantCell class. We will make another class CellDivision and access this method.

package creational.prototype;
* Shows how to use the clone.
public class CellDivision {
  public static void main(String[] args) {
PlantCell cell = new PlantCell();

// create a clone
PlantCell newPlantCell = (PlantCell)cell.split();

}// End of class

One thing is you cannot use the clone as it is. You need to instantiate the clone before using it. This can be a performance drawback. This also gives sufficient access to the data and methods of the class. This means the data access methods have to be added to the prototype once it has been cloned.

Creational Patterns
Factory Pattern
Abstract Factory Pattern
Singleton Pattern
Builder Pattern
Prototype Pattern
Structural Patterns
Adapter Pattern
Bridge Pattern
Composite Pattern
Decorator Pattern
Facade Pattern
Flyweight Pattern
Proxy Pattern
Behavioral Patterns
Chain of Responsibility Pattern
Command Pattern
Interpreter Pattern
Iterator Pattern
Mediator Pattern
Momento Pattern
Observer Pattern

State Pattern
Strategy Pattern
Template Pattern

Visitor Pattern
Use of this website constitutes acceptance of the Terms and Conditions