The intent of the prototype model is:
By giving a prototype object to indicate the type of object you want to create, you can then create more objects of the same type with the method of copying the prototype object.
This pattern has been implemented in the Java class Library, so long as you define a class that implements the Cloneable interface, objects created with this class can be used as prototype objects to clone more objects of the same type. Here is an example to introduce a simple introduction to its use.
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import Java.io.serializable;class Prototype implements cloneable,serializable{
Private String str;
Private Temp temp;
Public Object Clone () throws clonenotsupportedexception{//Shallow clone
Prototype prototype= (Prototype) Super.clone ();
return prototype;
}
Public Object Deepclone () throws ioexception,classnotfoundexception{//deep cloning
Bytearrayoutputstream bo=new Bytearrayoutputstream ();
ObjectOutputStream oo=new ObjectOutputStream (bo);
Oo.writeobject (this);
Bytearrayinputstream bi=new Bytearrayinputstream (Bo.tobytearray ());
ObjectInputStream oi=new ObjectInputStream (BI);
return Oi.readobject ();
}
Public String Getstr () {
return str;
}
public void Setstr (String str) {
This.str = str;
}
Public Temp gettemp () {
return temp;
}
public void Settemp (temp temp) {
This.temp = temp;
}
}
Class Temp implements serializable{
}
public class Test {
public static void Main (string[] args) throws Clonenotsupportedexception,classnotfoundexception, ioexception{
Prototype pt=new Prototype ();
Temp Temp=new temp ();
Pt.settemp (temp);
PT.SETSTR ("Hello World");
System.out.println ("Create objects with a shallow clone method");
Prototype pt1= (Prototype) Pt.clone ();
System.out.println ("=============================");
System.out.println ("Comparing the value of Str of PT and PT1:");
System.out.println (Pt.getstr ());
System.out.println (Pt1.getstr ());
System.out.println ("Modify the value of str in the Pt1 object to compare the values of PT and pt1 str:");
Pt1.setstr ("Hello, World");
System.out.println (Pt.getstr ());
System.out.println (Pt1.getstr ());
System.out.println ("============================");
System.out.println ("Comparing the value of the Temp object in PT and pt1");
System.out.println (Pt.gettemp ());
System.out.println (Pt1.gettemp ());
System.out.println ("Create object using deep cloning method");
System.out.println ("============================");
pt1= (Prototype) Pt.deepclone ();
System.out.println (Pt.gettemp ());
System.out.println (Pt1.gettemp ());
}
}