Prototype patterns of Java design patterns

Source: Internet
Author: User
Tags shallow copy

Prototype Pattern Concepts

The idea of this pattern is to use an object as a prototype, copy it, clone it, and produce a new object similar to the original object. Replication in Java is implemented through clone (). Deep, shallow replication is involved in clone. The concept of deep and shallow copying is as follows:

⑴ Shallow copy (shallow clone)

All the variables of the copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words, a shallow copy simply duplicates the object being considered, not the object it refers to. The object class provides a method that clones only copies this object, whether the array inside the object, the reference object, and so on are not copied, or the internal element address of the native object.

⑵ deep Copy (Deep clone)

All the variables of the copied object contain the same values as the original object, removing the variables that refer to other objects. Variables that refer to other objects will point to new objects that have been copied, not those that are already referenced. In other words, a deep copy copies the objects that are referenced by the object being copied again.

Prototype Pattern code
Package Com.roc.prototype;import java.io.Serializable;/** * Prototype mode programmer * @author LIAOWP **/ Public classProgrammer implements serializable,cloneable{/**     *      */    Private StaticFinalLongSerialversionuid =3078949912404836178L; PrivateString name;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicProgrammer Clone () throws Clonenotsupportedexception {Programmer proto=(Programmer) Super.clone (); returnProto; }  }

Let's write a shallow copy of the example below

Package Com.roc.prototype;/** * Address * @author LIAOWP **/ Public classaddress{PrivateString Province;//Province        PrivateString City;//City         PublicAddress (String province,string city) { This. province=Province;  This. city=City ; }     PublicString getprovince () {returnProvince; }     Public voidsetprovince (String province) { This. Province =Province; }     PublicString getcity () {returnCity ; }     Public voidsetcity (String city) { This. City =City ; } }
Package Com.roc.prototype;/** * Prototype mode programmer * @author LIAOWP **/ Public classProgrammer implements cloneable{PrivateString name;//name        Privateaddress address;  PublicProgrammer (String name,address Address) { This. name=name;  This. address=address; }         PublicAddress getaddress () {returnaddress; }     Public voidsetaddress (address address) { This. Address =address; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicObject Clone () throws Clonenotsupportedexception {Programmer proto=(Programmer) Super.clone (); returnProto; }      }
Package Com.roc.prototype;/** * Prototype mode * @author LIAOWP **/ Public classClient { Public Static voidMain (string[] args) throws Clonenotsupportedexception {//Shallow copy copyAddress address=NewAddress ("JX","GZ"); Programmer a=NewProgrammer ("LIAOWP", address); A.setaddress (NewAddress ("JX","GZ")); A.setname ("LIAOWP"); Programmer b=(Programmer) A.clone (); B.setname ("PWL"); B.getaddress (). Setprovince ("BJ"); System.err.println (B.getname ()+b.getaddress (). Getprovince ()); System.err.println (A.getname ()+a.getaddress (). Getprovince ()); }}

Output Result: PWLBJ

Liaowpbj

You can see the object and copy it, and still use the same reference. The array within its object, the reference object, and so on are not copied, or the internal element address of the native object. The following is a deep copy of the wording, deep copy has 2 kinds of writing, one is the object implementation cloneable, and the other is a binary stream. I wrote it all together.

Package Com.roc.prototype;/** * Prototype mode programmer * @author LIAOWP **/ Public classProgrammer implements cloneable{PrivateString name;//name        Privateaddress address;  PublicProgrammer (String name,address Address) { This. name=name;  This. address=address; }         PublicAddress getaddress () {returnaddress; }     Public voidsetaddress (address address) { This. Address =address; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicObject Clone () throws Clonenotsupportedexception {Programmer proto=(Programmer) Super.clone (); proto.address =(Address) Address.clone ();
returnProto; } }
Package Com.roc.prototype;/** * Address * @author LIAOWP **/ Public classAddress implements cloneable{PrivateString Province;//Province        PrivateString City;//City         Public        Object Clone () {address address = null;         Try  {Address = (address) super.clone (); }  catch  (clonenotsupportedexception e) {  //  TODO auto-generated catch bl        Ock  e.printstacktrace ();    }  return  address; }
PublicAddress (String province,string city) { This. province=Province; This. city=City ; } PublicString getprovince () {returnProvince; } Public voidsetprovince (String province) { This. Province =Province; } PublicString getcity () {returnCity ; } Public voidsetcity (String city) { This. City =City ; }

/* deep copy/binary notation, requires class serialization

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 out the new object generated by the binary stream */
Bytearrayinputstream bis = new Bytearrayinputstream (Bos.tobytearray ());
ObjectInputStream ois = new ObjectInputStream (bis);
return Ois.readobject ();
}

}

 PackageCom.roc.prototype;/*** Prototype mode *@authorLIAOWP **/ Public classClient { Public Static voidMain (string[] args)throwsclonenotsupportedexception {//Shallow copy copyAddress address=NewAddress ("JX", "GZ"); Programmer a=NewProgrammer ("Liaowp", address); A.setaddress (NewAddress ("JX", "GZ")); A.setname ("LIAOWP"); Programmer b=(Programmer) A.clone (); B.setname ("PWL"); B.getaddress (). Setprovince ("BJ"); System.err.println (B.getname ()+b.getaddress (). Getprovince ()); System.err.println (A.getname ()+a.getaddress (). Getprovince ()); }
}

Results: PWLBJ

Liaowpjx

The copy also has 2 knowledge points, and when the object is copied, the constructor of the class is not executed. A class Programmer that implements the Cloneable and writes the Clone method, has a parameterless structure or a parametric construct, generates an object A through the new keyword, and then produces a new object T by A.clone (), then the constructor is not used when the object is copied. Be executed. That is, only one construction method is executed during the copy process.

Clone vs final two pair of enemies. The object's clone is caused by a conflict with the final property within the object. In the programmer class above, modify to private final address address; Remove Get,set method, proto.address= (Address) Address.clone (); This sentence will be an error: proto.address= (address) address.clone (); The final type cannot reset the value. The solution is to erase the FINA.

Deep and shallow copies are not recommended for mixed use, some references in a class use a shallow copy for some references in a deep copy, which is a very poor design, especially when it comes to class inheritance, where the parent class has several references that are very complex, suggesting that deep and shallow copies are implemented separately.

Prototype patterns of Java design patterns

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.