Implementing Prototype pattern


Prototype pattern

Definition: the pattern is used to create a clone avoiding another creation. We clone the object if the cost of creating the object is expensive than cloning it.

Example:
participant classes:

  • Vinod.java
  • Rinku.java
  • Prototype.java
  • PrototpyeClient.java (client)

Diagram:


Prototype.java

This is an interface class defining signature for doClone() method. The return type is of Prototype type. This throws CloneNotSupportedException.

 public interface Prototype {
 public Prototype doClone() throws CloneNotSupportedException;
}

Vinod.java & Rinku.java

These are simple classes describing Vinod’s and Rinku’s characteristics. They have their attributes and their respective accessors defined in the class

These two classes implement the Prototype interface
doClone() method is implemented returning a new clone of the respective class

//Vinod.java
 public class Vinod implements Prototype,Cloneable{
 String name;
 String age;
 String sex;

 public String getName() {
 return "Vinod";
 }
 public String getAge() {
 return "25";
 }
 public String getSex() {
 return "Male";
 }
 @Override
 public Prototype doClone() throws CloneNotSupportedException {
 return (Prototype) this.clone();

 }

}

//Rinku.java

public class Rinku implements Prototype,Cloneable{
 String name;
 String age;
 String sex;

 public String getName() {
 return "Rinku";
 }
 public String getAge() {
 return "22";
 }
 public String getSex() {
 return "Female";
 }
 @Override
 public Prototype doClone() throws CloneNotSupportedException {
 return (Prototype) this.clone();

 }
}

PrototypeClient.java

Instantiating the objects and cloning the same

public class PrototypeClient {

 public static void main(String[] args) throws CloneNotSupportedException {

 Vinod vinod = new Vinod();
 Vinod vinod2 = (Vinod)vinod.doClone();

 System.out.println(vinod.hashCode() != vinod2.hashCode());
 System.out.println(vinod.getClass() == vinod2.getClass());

 }
}

contract:

x.clone() != x
x.clone().getClass() == x.getClass()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s