Prototype Pattern in Java
In the prototype pattern, a new object is created by cloning an existing object. In Java, the clone() method is an implementation of this design pattern. The prototype pattern can be a useful way of creating copies of objects. One example of how this can be useful is if an original object is created with a resource such as a data stream that may not be available at the time that a clone of the object is needed. Another example is if the original object creation involves a significant time commitment, such as reading data from a database. An added benefit of the prototype pattern is that it can reduce class proliferation in a project by avoiding factory proliferation. We can implement our own prototype pattern. To do so, we'll create a Prototype interface that features a doClone() method.
Declare the Prototype interface
package com.java.creational.prototype;
public interface Prototype {
public Prototype doClone();
}
The Person class implements the doClone() method.
This method creates a new Person object and clones the name field. It returns the newly cloned Person object.
package com.java.creational.prototype;
public class Person implements Prototype {
String name;
public Person(String name) {
this.name = name;
}
@Override
public Prototype doClone() {
return new Person(name);
}
public String toString() {
return "This person is named " + name;
}
}
The Cat class also implements the doClone() method. This method creates a new Cat object and clones the sound field. The cloned Cat object is returned.
package com.java.creational.prototype;
public class Cat implements Prototype {
String sound;
public Cat(String sound) {
this.sound = sound;
}
@Override
public Prototype doClone() {
return new Cat(sound);
}
public String toString() {
return "This cat says " + sound;
}
}
The Demo class creates a Person object and then clones it to a second Person object.
It then creates a Cat object and clones it to a second Cat object.
Write the Driver for the Interface and Class
package com.java.creational.prototype;
public class PrototypeExample {
public static void main(String[] args) {
Person person1 = new Person("Glenn");
System.out.println("person 1:" + person1);
Person person2 = (Person) person1.doClone();
System.out.println("person 2:" + person2);
Cat cat1 = new Cat("Meow");
System.out.println("cat 1:" + cat1);
Cat cat2 = (Cat) cat1.doClone();
System.out.println("cat 2:" + cat2);
}
}
Program output:
person 1:This person is named Glenn
person 2:This person is named Glenn
cat 1:This cat says Meow
cat 2:This cat says Meow