Alright, so you’re going to create a program but let’s say there’s a catch; you have several classes which may or may not be needed. Maybe you have a complex class on your hands or your classes are costly to instantiate. What’s a programmer to do-? Looking at the Gang of Four list, one pattern comes up at the top–the prototype!
A creational pattern, the prototype design pattern creates an independent clone by making a new object which copies all of the properties of an existing project.

Let’s look at an coded example using the prototype pattern. First we have our Animal interface. In order to use the prototype pattern, our interface extends the Cloneable interface from the Java library.
public interface Animal extends Cloneable {
public Animal makeCopy();
}
Next we create a CloneFactory class which takes elements that follow the Animal interface and returns the copy.
public class CloneFactory {
public Animal getClone(Animal animalSample) {
return animalSample.makeCopy();
}
}
Next we have the class Sheep which implements Animal. It overrides the inherited method makeCopy() and returns an object.
public class Sheep implements Animal {
public Sheep() {
System.out.println("Sheep is Made");
}
@Override
public Animal makeCopy() {
System.out.println("Sheep is Being Made");
Sheep sheepObject = null;
try {
sheepObject = (Sheep) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return sheepObject;
}
public String toString() {
return "Dolly is my hero, baaa";
}
}
Next we have TestCloning which is our main class; within the main method we create a sheep and a clone of the sheep. To prove we’re not just getting differently named but the same objects, we also display the hashcode for both ‘Sally’ the sheep and her clone.
public class TestCloning {
public static void main(String[] args) {
CloneFactory animalMaker = new CloneFactory();
Sheep sally = new Sheep();
Sheep clonedSheep = (Sheep) animalMaker.getClone(sally);
System.out.println(sally);
System.out.println(clonedSheep);
System.out.println("Sally Hashcode: " + System.identityHashCode(System.identityHashCode(sally)));
System.out.println("Clone Hashcode: " + System.identityHashCode(System.identityHashCode(clonedSheep)));
}
}