Prototype Design Pattern in Java
Instead of creating a new object from zero, you copy (clone) an existing object.
Real life example
Photocopying a filled form instead of writing it again.
When to use
Creating an object is slow or costly, and a copy of an existing object is faster.
Complete Java example
Save this as Main.java, then run javac Main.java and java Main.
public class Main {
public static void main(String[] args) {
Sheep dolly = new Sheep("Dolly");
Sheep copy = dolly.clone();
copy.name = "Dolly 2"; // original is not changed
System.out.println(dolly.name); // Dolly
System.out.println(copy.name); // Dolly 2
// Note: super.clone() is a shallow copy. Copy inner objects yourself if needed.
}
}
class Sheep implements Cloneable {
String name;
Sheep(String name) { this.name = name; }
public Sheep clone() {
try { return (Sheep) super.clone(); } // copies the object
catch (CloneNotSupportedException e) { throw new AssertionError(); }
}
}Output
Dolly
Dolly 2