Prototype mode definition:
Use a prototype instance to specify the object type and copy the prototype to create a new object.
The Prototype mode allows an object to create another custom object without any details. The working principle is: pass a Prototype object to the object to be created, the objects to be created are created by requesting the prototype objects to copy themselves.
How to use it?
Because the clone () method is provided in Java to clone objects, Prototype implementation becomes very simple.
Take a spoon as an example:
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 is a specific implementation (ConcretePrototype ):
Public class SoupSpoon extends actspoon { Public SoupSpoon () { SetSpoonName ("Soup Spoon "); } }
|
It is easy to call the Prototype mode:
AbstractSpoon spoon = new SoupSpoon ();
AbstractSpoon spoon2 = spoon. clone ();
Of course, you can also create a AbstractSpoon instance in the factory mode.
In Java, the Prototype mode becomes the use of the clone () method. The pure object-oriented feature of Java makes it natural to use the design mode in Java, the two are almost integrated. This is reflected in many modes, such as the Interator traversal mode.