Prototype: Use a prototype instance to specify the object type and copy the prototype to create a new object.
The class diagram is as follows:
We all know that the following code cannot create new objects. They all point to the same object.
Case code:
Domesticrobots. java
/*** Housework robot ** @ author wanghl **/public class Domesticrobots {private String mName; private String mVersion; public Domesticrobots (String name, String version) {mName = name; mVersion = version ;}@ Overridepublic String toString () {return Domesticrobots [mName = + mName +, mVersion = + mVersion +] + super. toString ();}}
Main. java
Public class Main {public static void main (String args []) {Domesticrobots robots1 = new robot (household robot 1, Terminator Generation 1); Domesticrobots robots2 = robots1; Domesticrobots robots3 = robots1; system. out. println (robots1); System. out. println (robots2); System. out. println (robots3 );}}
The output is as follows:
Domesticrobots [mName = housework robot 1, mVersion = Terminator Generation 1] Domesticrobots @ 3ce53?domesticrobots [mName = housework robot 1, mVersion = Terminator Generation 1] Domesticrobots @ Taobao [mName = housework robot 1, mVersion = Terminator Generation 1] Domesticrobots @ 3ce53108
If you want to produce household robots in batches, we can use the prototype.
In order to clone and produce household robots, we allow them to implement clone interfaces.
ICloneRobots. java
public interface IRobotsClone
{public T clone();}
The modified Domesticrobots class:
/*** Housework robot ** @ author wanghl **/public class Domesticrobots implements IRobotsClone
{Private String mName; private String mVersion; public Domesticrobots (String name, String version) {mName = name; mVersion = version ;}@ Overridepublic String toString () {return Domesticrobots [mName = + mName +, mVersion = + mVersion +] + super. toString () ;}public Domesticrobots clone () {return new Domesticrobots (mName, mVersion );}}
Test code:
Main. java
Public class Main {public static void main (String args []) {Domesticrobots robots1 = new Domesticrobots (housekeeping robot 1, Terminator Generation 1); Domesticrobots robotⅱ = robots1.clone (); domesticrobots robotsIII = robots1.clone (); System. out. println (robots1); System. out. println (robotⅱ); System. out. println (robotsIII );}}Print result:
Domesticrobots [mName = housework robot 1, mVersion = Terminator Generation 1] Domesticrobots @ 6af62373Domesticrobots [mName = housework robot 1, mVersion = Terminator Generation 1] Domesticrobots @ Taobao [mName = housework Robot, mVersion = Terminator Generation 1] Domesticrobots @ 55f33675
We can see that our robotⅱ and robotsIII are different objects.
The prototype mode allows you to create another object from one object without knowing the details of the Creation.