The Prototype Pattern in Java

Introduction to the Prototype Pattern

Design pattern in a simple meaning, is a way to design reusable object-oriented code. We can think of ways to design our classes, interfaces, enums and their members so that the code is reusable but flexible.

There are 23 most important design patterns, pioneered by the book Design Patterns: Elements of Reusable Object-Oriented Software, written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides or Gang of Four for short. We will cover these design pattern one by one.

By GoF definition, the Prototype pattern specifies the kinds of objects to create using a prototype, and create new objects by copying this prototype. This pattern provides a mechanism to copy the original object to a new object and then modify it according to our needs, using Java cloning method.

Implementation of Prototype pattern in Java

In our example, we will use the class Bike which implements the Cloneable interface:

public class Bike implements Cloneable{
  private String type;
  private String brand;
  public Bike clone()
      throws CloneNotSupportedException {
    return (Bike) super.clone();
  }
  public String getType() {
    return type;
  }
  public void setType(String type) {
    this.type = type;
  }
  public String getBrand() {
    return brand;
  }
  public void setBrand(String brand) {
    this.brand = brand;
  }
}

Now in Test.java we will create a Bike object, then we create another new Bike:

public class Test {
  public static void main(String[] args)
      throws CloneNotSupportedException {
    //create new bike
    Bike bike = new Bike();
    bike.setType("Regular Bike");
    bike.setBrand("Giant");
    //clone the basic Bike
    Bike basic = bike.clone();
    //output the basic Bike
    System.out.println("The basic Bike: " + 
      basic.getType() + " - " + basic.getBrand());
    //check if bike and basic are same object?
    System.out.println("Check bike and basic: "
      + (basic == bike));
  }
}

Run the code and we have:

Regular Bike - Giant
Check bike and basic: false

Leave a Reply