On the internet to find a lot of this model of information said is not thorough, looked at half a day is foggy. Had to study one by oneself.
Prototype mode is a creation design pattern that returns a new instance by copying an existing instance, rather than creating a new instance. The copied instance is what we call a prototype, which is customizable.
Prototype patterns are used to create complex or time-consuming instances, because in this case, copying an already existing instance can make the program run more efficiently, or create values equal, but with a different naming of similar data.
The copy in prototype mode is divided into "shallow copy" and "Deep copy":
Shallow copy: Copy the value of a member variable of a value type, copy only the reference to the member variable of the reference type, and do not copy the referenced object.
Deep copy: A copy of a value for a member variable of a value type, and a reference object for a member variable of a reference type.
Example:
Import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.io.serializable;public class Protype Implements cloneable,serializable{/** * */private static final long serialversionuid = 1l;public String name;public fuck F;public Protype (String name) {this.name = name;} Public Object Clone () {try {return super.clone (); } catch (Clonenotsupportedexception e) {e.printstacktrace (); return null; }} public Object Deepclone () {Bytearrayoutputstream out = new Bytearrayoutputstream (); ObjectOutputStream Objout;try { Objout = new ObjectOutputStream (out); Objout.writeobject (protype.this); Bytearrayinputstream in = new Bytearrayinputstream (Out.tobytearray ()); ObjectInputStream Objin = new ObjectInputStream ( in); return Objin.readobject ();} catch (IOException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (ClassNotFoundException e) {//Todo A Uto-generated CATch blocke.printstacktrace ();} return null;}}
Import java.io.Serializable; Public class Implements Serializable { /** * **/ privatestatic finallong serialversionuid = -3616639877050139128l; String fname; Public Fuck (String name) { = name; }}
Public classMain { Public Static voidMain (string[] args) {//TODO auto-generated Method StubProtype P1 =NewProtype ("P1"); P1.F=NewFuck ("Fuck1"); Protype P2=(Protype) P1.clone (); P2.name= "P2"; P2.f.fname= "Fuck2"; Protype P3=(Protype) P1.deepclone (); P3.name= "P3"; P3.f.fname= "Fuck3"; System.out.println ("P1.name=" +p1.name+ "p2.name=" +p2.name); System.out.println ("F1.name=" +p1.f.fname+ "f2.name=" +p2.f.fname); System.out.println ("F1.name=" +p1.f.fname+ "f3.name=" +p3.f.fname); }}
View Code
Results:
P1.NAME=P1 P2.NAME=P2
F1.name=fuck2 F2.name=fuck2
F1.name=fuck2 F3.name=fuck3
Java design pattern Four: Prototype mode (Prototype pattern)