Java language Implementation-created design pattern-prototype mode (PROTOTYPE)

Source: Internet
Author: User

First, describe

The prototype pattern is a prototype object that identifies the type of object to be created, and then copies the creation of more homogeneous objects using the method of copying the prototype object. For example, we have an object in the dynamic process of the program, which contains a series of valid data, we need a new object that is exactly the same as the object, and after the copy, there is no connection between the old and new objects, changes to any one object does not affect the other object.

All classes in Java inherit from the Java.lang.Object class by default, and there is a clone () method in the object class that returns a copy of the object.

We let the class that needs to be copied implement an interface that indicates that the Cloneable Object.clone () method can legitimately replicate the class instance by field. Cloneableinvoking the Clone method of Object on an instance that does not implement an interface causes an exception to be thrown CloneNotSupportedException .


Note : Thecloneable interface is a markup interface that has no other method, just as a token to indicate that the class can legitimately use the Clone () method of the object class to produce a copy of the instance.

In addition to the cloneable interface is the serializable interface (for classes to enable its serialization feature, classes that do not implement this interface will not be able to serialize or deserialize any of its states), The Randomaccess interface (the tag interface used in thelist implementation to indicate that it supports fast (usually fixed-time) random access, which provides good performance when applied to random or contiguous access lists), Remote Interface ( Remote an interface used to identify an interface whose methods can be called from a non-local virtual machine. Any remote object must implement this interface directly or indirectly. Only those methods specified in the remote interface (extended java.rmi.Remote interface) can be used remotely, the implementation class implements any number of remote interfaces, and other remote implementation classes can be extended. RMI provides useful classes that can be extended by remote object implementations that facilitate remote object creation.


Ii. advantages and disadvantages of prototype design pattern

Pros: In prototype mode, you can dynamically add product classes without affecting the whole day structure, just copying an object.

Cons: Because the prototype mode implements the interface for each class Cloneable and overrides the Clone () method in the object class, and the prototype pattern needs to be supplemented with more code when implementing a deep copy, this undoubtedly adds a certain amount of code.


Third, the source code

3.1 Shallow copy: If object types and reference types exist in the object being copied, only the addresses of the objects and reference types are copied, and the data in the objects and references is actually copied.

Package Tong.day5_1.dogcase;import java.util.arraylist;/** * Dogclone implements the Cloneable interface, overriding the Clone () method, invoking the parent class's Clone () Copying an object and returning it, the dog does not have a clone () method, which is a shallow copy of the pattern. * Shallow copy: The base data type does have another copy, but for the object type and reference type only copies the object or the referenced address, * the reference to the object type in the copied object points to the same object, as long as one is modified, it affects the data in the other object. * @author Tong * */public class Shallowclone {public static void main (string[] args) {//copy before data value Dogclone Dogclone = new D Ogclone (); System.out.println ("original dogclone.basiccount=" +dogclone.basiccount); System.out.println ("original dogclone.dog=" +dogclone.dog); System.out.println ("original dogclone.arraylist=" +dogclone.arraylist);D ogclone dogClone2 = (dogclone) dogclone.clone (); System.out.println ("-----------------------");//Changing the object type and reference type data in the copied object will affect the data of the other object; The base type is a copy of the value so that another copy is generated. There is no effect on the original data Dogclone2.basiccount = 2;dog Dog = Dogclone2.dog;dog.changecount ();d ogClone2.arrayList.add ("Java");// The value of the base data type in the original object is unchanged System.out.println ("later dogclone.basiccount=" +dogclone.basiccount); System.out.println ("later dogclone.dog=" +dogclone.dog); System.out.println ("The later dogclone.arraylist="+dogclone.arraylist); System.out.println ("dogclone2.basiccount=" +dogclone2.basiccount); System.out.println ("dogclone2.dog=" +dogclone2.dog); System.out.println ("dogclone2.arraylist=" +dogclone2.arraylist);} Class Dog{public int legcount;public Dog (int legcount) {this.legcount = Legcount;} public void Changecount () {This.legcount +=5;} Override the ToString () method of the dog class to call the method @overridepublic String ToString () {return integer.tostring (Legcount) when the dog object is output;} Dogclone implements the Cloneable interface, as long as you rewrite the Clone () in object to copy the object class Dogclone implements cloneable{// The basic data type copies a copy of the data value directly, that is, the Legcount value generated after the copy has no relation to the original copied value, the public int Basiccount;//dog object type, when the shallow copy is used, the address of the object in the stack is copied. Instead of the actual data of the heap memory pointed to by the object address public Dog dog = new Dog (5);//arraylist reference type, in shallow copy, copy only the referenced address, not the string public in the heap memory pointed to by the copy reference ArrayList <String> arrayList = new arraylist<string> ();p ublic Dogclone () {basiccount = 4;arraylist.add ("Hello"); Arraylist.add ("World");} Overridden Clone () to return a copy object of the Dogclone class @overrideprotected object Clone () {Dogclone Dogclone = null;try {Dogclone = (Dogclone) Super.clone ();} catch (Clonenotsupportedexception e) {e.printstacktrace ();} return dogclone;}}
Operation Result:



3.2 Deep Copy: Dogclone implements the Cloneable interface, overrides the Clone () method, invokes the parent class clone () to copy an object, and explicitly invokes the copy method of the dog object and the ArrayList object to return the class object. So the copy produced by the object and the original object will not interfere with each other, independent of each other.

Package Tong.day5_1.deepclone;import java.util.arraylist;/** * Dogclone implements the Cloneable interface, overriding the Clone () method, invoking the parent class's Clone () Copies an object and explicitly invokes the copy method of the dog object and the ArrayList object to return the class object, which is a deep copy pattern. * Deep copy: The basic data type does have a separate copy, but for object types and reference types the default is to copy only the object or the address of the reference, * if you want both types to also copy the data in the object and reference, then you need to override the Clone () method to explicitly call the object or the Clone () method of the reference type. * So we need to have the dog class implement the Cloneable interface so that it has the ability to copy, ArrayList indirectly inherits the object interface, itself has the Clone () method. * @author Tong * */public class Deepclone {public static void main (string[] args) {//copy before data value Dogclone Dogclone = new DOGC Lone (); System.out.println ("original dogclone.basiccount=" + Dogclone.basiccount); System.out.println ("original dogclone.dog=" + Dogclone.dog); System.out.println ("original dogclone.arraylist=" + dogclone.arraylist);D ogclone dogClone2 = (dogclone) dogclone.clone (); System.out.println ("-----------------------");//This is a deep copy, making changes to the object type and reference type data in the copied object without affecting the data of the other object; The base type is a copy of the value so that another copy is generated, and the original data is not affected Dogclone2.basiccount = 2;dog Dog = Dogclone2.dog;dog.changecount (); DogClone2.arrayList.add ("Java");//The value of all data in the original object is not changed System.out.println ("later dogclone.bAsiccount= "+ dogclone.basiccount); System.out.println ("later dogclone.dog=" + Dogclone.dog); System.out.println ("later dogclone.arraylist=" + dogclone.arraylist); System.out.println ("dogclone2.basiccount=" + dogclone2.basiccount); System.out.println ("dogclone2.dog=" + Dogclone2.dog); System.out.println ("dogclone2.arraylist=" + Dogclone2.arraylist);}} To implement a deep copy, we have the dog class implement the Cloneable interface and override the Clone () method in the interface class Dog implements cloneable {public int legcount;public dog (int Legcount) {this.legcount = Legcount;} public void Changecount () {this.legcount + = 5;} Override the ToString () method of the dog class to call the method @overridepublic String ToString () {return integer.tostring (Legcount) when the dog object is output;} Override the Clone () method so that its Dog object has the ability to copy itself @overrideprotected Object Clone () {Dog dog = null;try {dog = (dog) Super.clone ();} catch (Cl Onenotsupportedexception e) {e.printstacktrace ();} return dog;}} To make a copy of the Dogclone object, we let the Dogclone class implement the Cloneable interface and rewrite the Clone () method in object class Dogclone implements Cloneable {// A copy of the data value is copied directly from the base data type, meaning that the Legcount value generated after the copy has no relation to the original copied value. PuBlic int basiccount;//The Dog object type, when using a shallow copy, the address of the object in the stack is copied, not the actual data of the heap memory pointed to by the object address public dog dog = new Dog (5);//ArrayList reference type, In a shallow copy, copy only the referenced address instead of copying the string in the heap memory pointed to by the reference to public arraylist<string> ArrayList = new arraylist<string> ();p ublic Dogclone () {basiccount = 4;arraylist.add ("Hello"); Arraylist.add ("World");} Overridden Clone () to return a copy object of the Dogclone class @overrideprotected object Clone () {Dogclone Dogclone = null;try {dogclone = (dogclone) Super.clone ();} catch (Clonenotsupportedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} The Clone () of the dog object is explicitly called to return a copy of the Dog object Dogclone.dog = (dog) dog.clone ();//explicitly invokes the clone of the ArrayList object () Returns a copy of a ArrayList object dogclone.arraylist = (arraylist<string>) arraylist.clone (); return dogclone;}}
Operation Result:





Java language Implementation-created design pattern-prototype mode (PROTOTYPE)

Related Article

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.