Prototype pattern definition: Use prototype instances to specify the type of objects to be created, and create new objects by copying these prototypes.
Prototype mode allows an object to create another customizable object without knowing any details of how to create it. The working principle is: by passing a prototype object to the object to be started, the object to be started to create is requested by requesting the prototype. Object copy and create them yourself.
How to use prototype mode
Because Java provides clone() method to implement object cloning, the implementation of Prototype mode suddenly becomes very simple. Take the spoon as an example:
The code copy is as follows:
public abstract class AbstractSpoon implements Cloneable{
String spoonName;
public void setSpoonName(String spoonName) {this.spoonName = spoonName;}
public String getSpoonName() {return this.spoonName;}
public Object clone(){
Object object = null;
try {
object = super.clone();
} catch (CloneNotSupportedException exception) {
System.err.println("AbstractSpoon is not Cloneable");
}
return object;
}
}
There are two concrete implementations (ConcretePrototype):
The code copy is as follows:
public class SoupSpoon extends AbstractSpoon{
public SoupSpoon(){
setSpoonName("Soup Spoon");
}
}
public class SaladSpoon extends AbstractSpoon{
public SaladSpoon(){
setSpoonName("Salad Spoon");
}
}
Calling Prototype mode is simple:
The code copy is as follows:
AbstractSpoon spoon = new SoupSpoon();
AbstractSpoon spoon = new SaladSpoon();
Of course, you can also combine factory mode to create AbstractSpoon instances.
In Java, the use of Prototype pattern becomes clone() method. Due to the pure object-oriented nature of Java, it becomes very natural to use design patterns in Java, and the two are almost integrated. This is reflected in many modes, such as the Interator traversal mode.