Prototype Design Pattern in Java

This design pattern works to the truest sense of the word ‘Prototype’. Another one of the creational design patterns, the Prototype Design Pattern finds use, where there is a requirement of creating numerous objects, and all of them, will have same or similar attributes. In such cases, a prototype object is created with generalized behaviors. This structure is then copied or cloned to make objects. In simpler words, the Prototype structure can be thought of as an object template factory.

Definition

The Prototype design pattern in Java produces a prototype object with sample attributes, traits, and parameters. Thereafter, any object that has similar attributes can be created by simply cloning the prototype object. Not only does this structure make object creation easy but also abstracts the complex object instantiation process from clients.

This approach is preferred as object creation is costlier than cloning. JAVA has made it even easier to implement this pattern in your code. The clone() method is a quick and effective tool for cloning. However, there are other cloning techniques as well.

Components of the Prototype Design Pattern

  • Prototype: This contains the prototype of an object.
  • Prototype Registry: This registry keeps a record of all prototypes using string inputs.
  • Client: The client refers to the registry to make objects.

Example and Code

This example will have a general vehicle class which will extended by particular models of cars.

import java.util.LinkedList;
import java.util.List;

abstract class Vechicle implements Cloneable {
private String carName;
Abstract void addCar();
public Object clone() {
Object clone = null;

try {
clone = super.clone(); }
catch (CloneNotSupportedException e) {
e.printStackTrace(); }
return clone;
}
}

class toyota extends Vehicle {
public Toyota()
{ this.carName = “Toyota”; }

@Override
void addCar()
{ System.out.println(“A Toyota car has been added”) ; }
}




class honda extends Vehicle {
public Honda()
{ this.carName = “Honda”; }

@Override
void addCar()
{ System.out.println(“A Honda car has been added”) ; }
}

/* Now add the vehicle types to a linked list, the imports for which have been mentioned at the start of the program and print out the different names by calling the individual car classes i.e. the Toyota and the Honda Class*/

 

When to use the Prototype Design Pattern?

This pattern should be followed when a large number of similar objects need to be created and creating new instances each time is not feasible. This will also keep the code independent of the end-products.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.