Prototype Pattern Definition: Specifies the type of object to create with a prototype instance, and creates a new object by copying the prototypes.
The prototype mode allows one object to create another customizable object without having to know any details of how it was created, working by passing a prototype object to the object to be created, and creating the object by requesting the prototype object to copy themselves.
How to use prototype mode
Because the Java provides the clone () method to implement the object cloning, the prototype pattern implementation suddenly becomes very simple. Take a spoon for example:
Copy Code code 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 = null;
try {
Object = Super.clone ();
catch (Clonenotsupportedexception exception) {
System.err.println ("Abstractspoon is not cloneable");
}
return object;
}
}
There are two specific implementations (CONCRETEPROTOTYPE):
Copy Code code as follows:
public class Soupspoon extends abstractspoon{
Public Soupspoon () {
Setspoonname ("Soup spoon");
}
}
public class Saladspoon extends abstractspoon{
Public Saladspoon () {
Setspoonname ("Salad spoon");
}
}
Calling the prototype pattern is simple:
Copy Code code as follows:
Abstractspoon spoon = new Soupspoon ();
Abstractspoon spoon = new Saladspoon ();
Of course, you can also combine factory patterns to create Abstractspoon instances.
In Java, the prototype pattern becomes the use of the Clone () method, because Java's pure object-oriented features make it natural to use design patterns in Java, both of which are almost seamless. This is reflected in many modes, such as Interator traversal mode.