The prototype pattern of Java design pattern "Prototype pattern"

Source: Internet
Author: User

First, overview:

Use the prototype instance to specify the kind of objects that are created, and create new objects by copying those prototypes. Simply put, a copy of the object creates a new object (the clone of the object), and the prototype pattern is an object-creation pattern .


Second, the use of the scene:

Creating a new object can be obtained by copying an existing object and, if it is a similar object, simply modify its member variables slightly.


Third, UML structure diagram:



Iv. participants

(1) Prototype (Abstract prototype Class): It is the interface that declares the cloning method, is the public parent class of all concrete prototype classes, can be abstract class can be an interface, even can be a concrete implementation class.

(2) Concreteprototype (Concrete prototype Class): It implements the Clone method declared in the abstract prototype class, and returns its own clone object in the Clone method.

(3) Client (Customer Class): Let a prototype object clone itself to create a completely new object.


V. Use case LEARNING:

1. Abstract Prototype class: Prototype.java

/** * Abstract Prototype class * @author  [email protected] * */public abstract class Prototype {/** * provides an abstraction Clone method */public abstract Prototyp e clone ();}
2, Concrete prototype class: Concreteprototypea.java

/** * Specific Prototype Class A * @author  [email protected] * */public class Concreteprototypea extends Prototype {/** * Shallow clone */@Overridep Ublic Prototype Clone () {Prototype Prototype = new Concreteprototypea (); return Prototype;}}
3. Client Test class: Client.java

public class Client {public static void main (string[] args) {Prototype Prototypea = new Concreteprototypea (); Prototype Prototypeb = Prototypea.clone (); System.out.println (Prototypeb.equals (Prototypea));   Return FalseSystem.out.println (Prototypeb = = Prototypea);   Return FalseSystem.out.println (prototypeb.getclass () = = Prototypea.getclass ());  Return true}}
Here we can see that the Prototypea object has cloned an object PROTOTYPEB, but Prototypea! = Prototypeb, stating that PROTOTYPEB is a new prototype object.


Note: The objects created by the prototype pattern through the Clone method are completely new objects that have new addresses in memory, and often modifications to the objects produced by the clones have no effect on the prototype object, each of which is independent of each other.


Vi.. Expansion:

A brief introduction to shallow cloning and deep cloning:

(1) In the Java language, data types are categorized into value types (base data types) and reference types , and value types include simple data types such as int, double, Byte, Boolean, char, reference types include classes, interfaces, Arrays and other complex types. The following person object:

public class Person {//name private String name;//age private int age;//His father private Father Father;}

Name, age is the base data type, and father is the reference type.

The primary difference between shallow and deep clones is whether to support replication of member variables of reference types


(2) Shallow cloning:

In the Java language, a shallow clone is implemented by overriding the Clone () method of the object class, in a shallow clone, when the object is copied, only the member variables of itself and the value types contained therein are copied, and the member objects of the reference type are not copied. This means that the prototype object simply copies the address of the reference object to the cloned object, and the reference type member variable of the cloned object and the prototype object is also pointing to the same memory address.

Note : Java classes that can implement cloning must implement an identity interface, cloneable, to indicate that the Java class support is being replicated. If a class does not implement this interface but invokes the Clone () method, the Java compiler throws a clonenotsupportedexception exception.


To speak in code:

1. Reference object: Father.java

public class father{//name private String name;//ages private int age;public Father (String name, int age) {this.name = name;th Is.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}
2. Clone prototype class: Person.java

public class person implements cloneable{//name private String name;//age private int age;//His father private Father father;/** * Override the Object object's clone method to implement the clone of the person object, */public person Clone () {Object obj = null;try {obj = Super.clone (), return (person) obj;} c Atch (clonenotsupportedexception e) {e.printstacktrace ();} return null;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public Father Getfather () {return Father;} public void Setfather (Father Father) {this.father = Father;}}
3. Test class: Cloneclient.java

public class Cloneclient {public static void main (string[] args) {Father Father = new Father ("Lao Tzu", 50); person son = new person (), Son.setname ("Son"), Son.setage ("Son.setfather"); father;//Shallow clone a brother person Object person Brother = Son.clone (); System.out.println (brother = son);  Return FalseSystem.out.println (brother.getfather () = = Son.getfather ());  Return true}}
above we can analyze to see son shallow cloned a "brother" object brother, but their reference object "Father" is the same object, all the facts prove that shallow clones do not copy the reference type Object .


(3) Deep cloning:

In a deep clone, regardless of whether the member variable of the prototype object is a value type or a reference type, all of the member variables contained in the object are copied in a deep clone, except that the object itself is copied.


So how to achieve deep cloning?

In the Java language, if you need to implement deep clones, you can do so through serialization (serialization) . Serialization is the process of writing an object to a stream, and the object written to the stream is a copy of the original object, and the original object still exists in memory. A copy implemented by serialization can not only copy the object itself, but also copy its referenced member objects, so it can be deeply cloned by serializing the object into a stream and then reading it out of the stream. It is important to note that objects that are capable of serializing have their classes implemented with the Serializable interface, otherwise they cannot implement serialization operations .


To speak in code:

1. Reference class: Father.java

Import Java.io.serializable;public class Father implements serializable{//name private String name;//age private int Age;pub Lic Father (String name, int age) {this.name = Name;this.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;}}
2.Clone Prototype class: Person.java

Import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.io.optionaldataexception;import Java.io.serializable;public class Person implements serializable{//name private String name;//age private int age;//his father pri Vate Father father;/** * Deep clone * @return * @throws IOException * @throws classnotfoundexception * @throws optionaldataexcept Ion */public Person Deepclone () throws IOException, ClassNotFoundException, optionaldataexception{//write object to stream B       Ytearrayoutputstream bao=new Bytearrayoutputstream ();       ObjectOutputStream oos=new ObjectOutputStream (Bao);             Oos.writeobject (this);       Remove the object from the stream bytearrayinputstream bis=new Bytearrayinputstream (Bao.tobytearray ());       ObjectInputStream ois=new ObjectInputStream (bis); return (person) ois.readobject ();} Public String GetName () {return name;} public void SetName (String name) {this.name = Name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public Father Getfather () {return Father;} public void Setfather (Father Father) {this.father = Father;}}
3, deep cloning test class: Deepcloneclient.java

public class Deepcloneclient {public static void main (string[] args) {Father Father = new Father ("Lao Tzu", 50); person son = new person (), Son.setname ("Son"), Son.setage (Son.setfather), father; try {person brother = Son.deepclone () ; System.out.println (brother = son);  FalseSystem.out.println (brother.getfather () = = Son.getfather ());  False} catch (Optionaldataexception e) {e.printstacktrace ();} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}
above we can analyze to see through the deep cloning of "brother" object not only the brother and son, but even their reference type father also unequal. All proof: clones a completely new object with deep clones.


The prototype pattern of Java design pattern "Prototype pattern"

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.