The prototype pattern of Java design pattern "Prototype pattern"

Source: Internet
Author: User
Tags object object

First, overview:

Use the prototype instance to specify the kind of object to create, and create a new object by copying the 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, assuming that it is a similar object, only a minor change to its member variables is required.


Third, UML structure diagram:



Iv. Participant

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

(2) Concreteprototype (Detailed prototype Class): It is now the Clone method declared in the abstract prototype class. Returns one of its cloned objects 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, the detailed prototype class: Concreteprototypea.java

/** * Detailed prototype Class A * @author  [email protected] * */public class Concreteprototypea extends Prototype {/** * light clone */@Overridep Ublic Prototype Clone () {Prototype Prototype = new Concreteprototypea (); return Prototype;}}
3, the 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 changes to the objects produced by the clones have no effect on the prototype object. Each cloned object is independent of each other.


Vi.. Expansion:

Brief introduction of Shallow clone and deep clone:

(1) In the Java language. Data types are divided into value types (base data types) and reference types . Value types contain simple data types such as int, double, Byte, Boolean, Char, and so on. Reference types contain complex types such as classes, interfaces, arrays, and so on.

For example, 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. By overriding the Clone () method of the object class, you implement a shallow clone, in a shallow clone, when the object is copied, it simply copies itself and the member variables of the value type included in it. The member object of the reference type is not copied. that is, 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 still points to the same memory address.

Note : Java classes that can implement cloning must implement an identity interface, cloneable, to indicate that this Java class support is replicated. Suppose 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 clone does 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, a copy is copied to the Clone object, simply speaking, in a deep clone. All member variables included in the object are copied, in addition to the object itself being copied.


So how to achieve deep cloning?

In the Java language. Imagine the need for deep cloning. Can be implemented by means of serialization (serialization) . Serialization is the process of writing an object to a stream. The object written to the stream is a copy of the original object, and the original object still exists in memory.

A copy that is implemented by serialization can not only copy the object itself, but also copy its referenced member objects, so it is serialized to write the object into a stream and then read it out of the stream. Able to achieve deep cloning. It is important to note that the object whose class is capable of serializing must implement the Serializable interface. Otherwise, the serialization operation cannot be implemented .


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 the "brother" object through deep cloning brother and son not only unequal, but even their reference type father.

Full proof: clones a completely new object with deep cloning.




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.