What is Prototype
It is known as Clone. Prototype is a creational design pattern that enables you copy/clone existing object to create new objects.
Example
Given below exmpale shows how Prototyp works. Here I created Animal Interface that extends Cloneable. Dog and Sheep both implement Animal as well as it’s makeCopy method. CloneFactory playing as broker and it offers getClone (super.clone()) method to return the copy object of its input Animal parameter.
Animal Interface
java1
2
3public interface Animal extends Cloneable {
public Animal makeCopy();
}Dog, it implements Animal. From makeCopy method, it use super.clone() to clone existing object.
java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public class Dog implements Animal{
public Dog(){
System.out.println("Dog is Made");
}
public Animal makeCopy() {
System.out.println("Dog is being made");
Dog dog = null;
try {
dog = (Dog) super.clone(); // use clone method to clone object
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return dog;
}
public String toString(){
return "A Dog!";
}
}Sheep, the same structure with Dog class
java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public class Sheep implements Animal{
public Sheep(){
System.out.println("Sheep is Made");
}
public Animal makeCopy() {
System.out.println("Sheep is being made");
Sheep sheep = null;
try {
sheep = (Sheep) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return sheep;
}
public String toString(){
return "A Sheep";
}
}CloneFactoy
java1
2
3
4
5public class CloneFactory {
public Animal getClone(Animal animal){
return animal.makeCopy();
}
}TestCloning
java1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18public class TestCloning {
public static void main(String[] args) {
//crete facory instance
CloneFactory cloneFactory = new CloneFactory();
Sheep sheep = new Sheep();
Sheep clonedSheep = (Sheep) cloneFactory.getClone(sheep);
// sheep and clonedSheep are having the different hashcode which means they are different object.
System.out.println(sheep.hashCode());
System.out.println(clonedSheep.hashCode());
Dog dog = new Dog();
Dog clonedDog = (Dog) cloneFactory.getClone(dog);
System.out.println(dog.hashCode());
System.out.println(clonedDog.hashCode());
}
}








