Prototype Pattern: Prototype Pattern and prototypepattern

Source: Internet
Author: User

Prototype Pattern: Prototype Pattern and prototypepattern

I. Overview:

Use a prototype instance to specify the type of the object to be created and copy the prototype to create a new object. Simply put, an object is copied to generate a new object (Object cloning). The prototype is an object creation mode.


II. Application scenarios:

You can create a new object by copying an existing object. For a similar object, you only need to modify its member variables.


Iii. UML structure diagram:



4. Participants

(1) Prototype (Abstract Prototype class): it is the interface for declaring the clone method. It is the common parent class of all the specific Prototype classes. It can be an abstract class or an interface, it can even be a specific implementation class.

(2) ConcretePrototype: it implements the clone method declared in the abstract prototype class and returns a clone object of its own in the clone method.

(3) Client (customer class): allows a prototype object to clone itself to create a new object.


V. Use Case Learning:

1. Abstract Prototype: Prototype. java

/*** Abstract Prototype class *** @ author lvzb.software@qq.com ***/public abstract class Prototype {/*** provides the abstract clone method */public abstract Prototype clone ();}
2. Specific prototype: ConcretePrototypeA. java

/*** Specific Prototype class A * @ author lvzb.software@qq.com **/public class ConcretePrototypeA extends Prototype {/*** shortest clone */@ Overridepublic 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 cloned an object prototypeB, but prototypeA! = PrototypeB indicates that prototypeB is a new Prototype object.


Note: In prototype mode, the objects created by cloning are brand new objects with new addresses in the memory, modifications to the cloned objects do not affect the prototype objects. Each cloned object is independent of each other.


Vi. Expansion:

Brief Introduction to shortest cloning and deep cloning:

(1) in Java, data types include value type (basic data type) and reference type. value types include int, double, byte, boolean, char, and other simple data types, 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 and age are the basic data types, and father is the reference type.

The major difference between shortest cloning and deep cloning is whether copying of referenced member variables is supported.


(2) cloning:

In Java, the clone () method that overwrites the Object class is used to implement the shortest clone. In the shortest clone, when an object is copied, only the member variables of its own and its value types are copied, but the Member objects of the reference type are not copied, that is to say, the prototype object only copies the address of the referenced object to the cloned object. The reference type member variables of the cloned object and the prototype object still point to the same memory address.

Note: The cloned Java class must implement a Cloneable interface, indicating that the Java class can be copied. If a class does not implement this interface but the clone () method is called, the Java compiler will throw a CloneNotSupportedException exception.


Use code to speak:

1. reference object: Father. java

Public class Father {// name private String name; // age private int age; public 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 age) {this. age = age ;}}
2. Clone prototype: Person. java

Public class Person implements Cloneable {// name private String name; // age private int age; // his Father private father Father; /*** rewrite the Object clone method to clone the Person Object */public Person clone () {Object obj = null; try {obj = super. clone (); return (Person) obj;} catch (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 age) {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 (24); son. setFather (father); // clone a sibling Person object: Person brother = son. clone (); System. out. println (brother = son); // return falseSystem. out. println (brother. getFather () = son. getFather (); // return true }}
From the above analysis, we can see that son cloned a "brother" Object brother, but their reference object "father" is the same object, all facts show that the shortest clone does not copy the object of the reference type.


(3) Deep clone:

In deep cloning, no matter whether the member variables of the prototype are value type or reference type, a copy is copied to the cloned object. In simple words, in deep cloning, in addition to the object itself being copied, all member variables contained in the object will also be copied.


How can we achieve deep cloning?

In Java, deep cloning can be achieved through Serialization. Serialization is the process of writing an object to the stream. The object written to the stream is a copy of the original object, and the original object still exists in the memory. The copy implemented by serialization not only copies the object itself, but also copies the referenced Member objects. Therefore, the object is written to a stream through serialization and then read from the stream, deep cloning is supported. Note that the class of the object that can be serialized must implement the Serializable interface; otherwise, the serialization operation cannot be implemented.


Use code to speak:

1. Reference class: Father. java

Import java. io. serializable; public class Father implements Serializable {// name private String name; // age private int age; public 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 age) {this. age = age ;}}
2. Clone prototype: 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 private father Father; /*** deep clone * @ return * @ throws IOException * @ throws ClassNotFoundException * @ throws OptionalDataException */public Person deepClone () throws IOException, ClassNotFoundException, optionalDataException {// write the object into the stream ByteArrayOutputStream bao = new ByteArrayOutputStream (); ObjectOutputStream oos = new ObjectOutputStream (bao); oos. writeObject (this); // retrieves 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 age) {this. age = age;} public Father getFather () {return father;} public void setFather (Father father) {this. father = father ;}}
3. Deep clone 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 (24); 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 ();}}}
From the above analysis, we can see that the brother and son objects cloned in depth are not only unequal, but also their reference type Father. All proofs: a completely independent new object is cloned through deep cloning.



In Java, what are the 23 design patterns that must be understood?

1. Simple Factory Pattern)
2. Builder Pattern)
3. Strategy Mode
4. Factory Method Pattern)
5. Abstract Factory)
6. Command Pattern)
7. Template Method)
8. Single Pattern)
9. Prototype Pattern)

What are the 23 Java design patterns?

There are 23 design modes in total!

Reference the "software secrets-the point of design patterns" book:

According to the purpose, the design patterns can be divided into creation patterns, structural patterns, and behavior patterns.
The creation mode is used to process the object creation process, the structure mode is used to process the combination of classes or objects, and the behavior mode is used to describe how classes or objects interact and how responsibilities are assigned.

The creation mode is used to process the object creation process. It mainly includes the following five design modes:
Factory Method Pattern)
Abstract Factory Pattern)
Builder Pattern)
Prototype Pattern)
Singleton Pattern)

The structural mode is used to process the combination of classes or objects. It mainly includes the following seven design modes:
Adapter Pattern)
Bridge Pattern)
Composite Pattern)
Decorator Pattern)
Facade Pattern)
Flyweight Pattern)
Proxy Pattern)

The behavior pattern is used to describe how classes or objects interact and how responsibilities are assigned. It mainly includes the following 11 design patterns:
Chain of Responsibility Pattern)
Command Pattern)
Interpreter mode (Interpreter Pattern)
Iterator Pattern)
Mediator Pattern)
Memory memorandum mode (Memento Pattern)
Observer Pattern)
State Pattern)
Strategy Pattern)
Template Method Pattern)
Visitor Pattern)

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.