Java prototyping mode

Source: Internet
Author: User
Tags shallow copy

prototype mode (PROTOTYPE): Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototypes.


Prototype pattern structure diagram

In layman's terms: prototype patterns are the implementation of deep and shallow copies.

Shallow copy

Only value copies are implemented, for reference objects or for original objects.

    • The parent class implements the Clone method, and the subclass does not implement the Clone method, and the effect is a shallow copy.
    • The parent class implements the Clone method, the subclass also implements the Clone method, originally I thought should be the deep copy, did not think also is the shallow copy .
Package com.prototype;Import java.io.Serializable;PublicClassWorkImplementsSerializable,cloneable{PrivateStaticFinalLong Serialversionuid =207835812839542204L;Private String job;PrivateDouble salary;PublicWork(String job,Double salary) {This.job = job;This.salary = salary; }@OverridePublic StringTostring() {Return"Work [job=" + Job +", salary=" + salary +"]"; }public String getjob () {return job; } public void setjob (String job) {this.job = Job;} public double getsalary () {return salary;} public void setsalary (double salary) {this.salary = salary; }} 
Package com.prototype;Import java.io.Serializable;PublicClassUserImplementsSerializable,cloneable{PrivateStaticFinalLong Serialversionuid =-2260332138558500447L;Private String name ="";Private work Work =NullPublicUser(String name,string Job,Double salary) {This.name=name; Work =New work (Job, salary); }PublicvoidChangejob(String Job) {This.work.setJob (Job); }/* Just implement the Cloneable interface, overwrite the Clone method, where the Clone method can be changed to any name, because the Cloneable interface is an empty interface, you can arbitrarily define the method name of the implementation class, such as Clonea or Cloneb. The point is Super.clone (), Super.clone () invokes the Clone () method of object, whereas in the object class, Clone () is native. *///Shallow copy: After copying an object, the variables of the base data type are recreated, and the reference type, pointing to the original object. @Override protected Object clone() throws clonenotsupportedexception { return super.clone ( ); } @Override public String toString() { return ' User [name= + name + ', work= ' + work + "]"; }}
Package com.prototype;PublicClassMain {public static void main (string[] args) { try {User User1 = new User ( " Zhangsan ", " CEO ", 100000); User User2 = (user) user1.clone (); System. out.println (user1); System. out.println (User2); System. out.println ( "Modify Job"); User2.changejob ( out.println (user1); System. out.println (User2);} catch (clonenotsupportedexception e) {e.printstacktrace ();}}     
//结果User [name=zhangsan, work=Work [job=ceo, salary=100000.0]]User [name=zhangsan, work=Work [job=ceo, salary=100000.0]]修改jobUser [name=zhangsan, work=Work [job=cfo, salary=100000.0]]User [name=zhangsan, work=Work [job=cfo, salary=100000.0]]
Deep copy

That is, a value copy is implemented, and a copy of the referenced object is also implemented.

    • Fayi
    //deep copy: After copying an object, both the base data type and the reference type are recreated.    //for deep replication, you need to read the binary input of the current object in the form of a stream, and then write out the object corresponding to the binary data. public Object deepClone () throws IOException, classnotfoundexception{ //writes the binary stream of the current object Bytearrayoutputstream bos = new Bytearrayoutputstream (); ObjectOutputStream Oos = new ObjectOutputStream (BOS); Oos.writeobject (this); //read into the new object generated by the binary stream Bytearrayinputstream bis = new Bytearrayinputstream (Bos.tobytearray ()); ObjectInputStream ois = new ObjectInputStream (bis); return ois.readobject ();}          
    • Law II
    //将User的拷贝方法修改为下面的方法。    @Override    protected Object clone() throws CloneNotSupportedException { Work w = (Work) work.clone();//对其引用变量进行拷贝 User u = (User)super.clone();//自身拷贝 u.work = w;//引用变量重新赋值。 return u; }



===================================================
    • Defined

      Use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes.

    • Usage Scenarios

      The prototype pattern is used on objects that are frequently called and very similar, and it clones objects and sets the changed properties, and consumes less resources.

    • code example implementation

Prototypeimpl.java

 Package com.design.prototype;PublicClassPrototypeimplImplementscloneable{Privateint shallowclone;Private Deepclone Deepclone =New Deepclone ();PublicPrototypeimpl() {System.out.println ("Construct is called"); }PublicvoidPrint() {TODO auto-generated Method Stub System.out.println (Shallowclone); System.out.println (Deepclone.gets ()); }@OverrideProtected PrototypeimplClone(){TODO auto-generated Method Stubtry{Prototypeimpl prototypeimp = (Prototypeimpl)super.clone (); //prototypeimp.shallowclone = This.shallowclone; //prototypeimp.deepclone = This.deepClone.clone (); return Prototypeimp;} catch (Exception e) {e.printstacktrace (); return null;} public void setshallowclone (int ShallowClone) {this.shallowclone = Shallowclone;} public void sets (String s) {deepclone.sets (s);}}     

Deepclone.java

Package com.design.prototype;PublicClassDeepcloneImplementscloneable{Private String S;Public StringGetS () {return s;} public void sets (String s) {THIS.S = s;}  @Override protected DeepClone Span class= "Hljs-title" >clone () {//TODO auto-generated method Stub try {return (deepclone)  Super.clone (); } catch (clonenotsupportedexception e) {//TODO Auto-generated Catch block E.printstacktrace (); } return null;}        

App.java

Package com.design.prototype;PublicClassApp {public static void main (string[] args) { //TODO auto-generated method stub Prototypeimpl prototypeimp =  New Prototypeimpl (); Prototypeimp.setshallowclone (1) prototypeimp.sets ( "deep Clone "); Prototypeimp.print (); System. out.println ( "-------------"); Prototypeimpl PROTOTYPEIMP2 = Prototypeimp.clone (); Prototypeimp2.setshallowclone (2) prototypeimp2.sets ( "deep Clone 2 "); Prototypeimp2.print (); System. out.println ( "-------------"); Prototypeimp.print ();}}   
    • Results analysis

Running result 1.png
    1. This is mainly due to the fact that the normal type of data is not a problem, and the object type is problematic. At the same time we should notice that the constructor is not called when clone is in.

    2. Remove the two lines of prototypeimpl.clone comments (the first line is nothing, but add, there is a contrast)


      Running result 2.png
    3. Summarize pros and cons
      • Advantages
        The prototype pattern is a copy of the binary stream in memory, which is much better than the direct new one, especially when a large number of objects are produced in a loop, and the prototype pattern can be more representative of its point.
      • Disadvantages
        It is necessary to keep in mind that constructors are not called, so you should do more with the constructor, and with the problem of deep copy.



Wen/lguipeng (author of Jane's book)
Original link: http://www.jianshu.com/p/062023c33d77
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Java prototyping mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.