Prototype Pattern and prototypepattern

Source: Internet
Author: User

Prototype Pattern and prototypepattern

Finally, CSDN was chosen to sort out the knowledge points published over the past few years. This article was migrated to CSDN in parallel. Because CSDN also supports the MarkDown syntax, it's awesome!

[Craftsman if water http://blog.csdn.net/yanbober] read the previous article "design mode (Creation) Builder mode (Builder Pattern)" http://blog.csdn.net/yanbober/article/details/45338041

Overview

To understand the prototype mode, you must first understand the shortest replication and deep replication in Java. In some cases, replication is also called cloning. Java provides these two cloning methods. Because the clone () method is provided in Java to clone objects, Prototype implementation becomes very simple at once.

Shortest clone:All the variables of the cloned object contain the same value as the original object, and all its references to other objects still point to the original object. In other words, the shortest clone only clones the objects to be considered, rather than the objects referenced by it.

Deep clone:All the variables of the cloned object contain the same value as the original object, but all its references to other objects are no longer original, and this is a new object that has been copied. In other words, deep replication copies all referenced objects of the objects to be copied. This is called indirect replication.

The following conditions must be met:

The implementation of clone () in java should meet the above three conditions (the first two are required, and the third is recommended but not mandatory ).

Core

Concept:Use a prototype instance to specify the type of the object to be created and copy the prototype to create a new object. The prototype mode is an object creation mode.

Important:Important core modules of the prototype structure:

Implement the Cloneable Interface

There is a Cloneable interface in java, which has only one function. It notifies virtual machines at runtime that they can safely use the clone method in the class implementing this interface. In a Java virtual machine, only classes that implement this interface can be copied. Otherwise, a CloneNotSupportedException exception will be thrown during runtime.

Override the clone method in the Object class

In Java, the parent class of all classes is an Object class, and the Object class has a clone method to return a copy of the Object, but its scope of the protected type, the general class cannot be called, therefore, the Prototype class must modify the clone method scope to the public type.

Use Cases

Creating a new object is costly (for example, initialization takes a long time and occupies too many CPU resources or network resources ), the new object can be obtained through copying existing objects in prototype mode. If it is a similar object, You Can slightly modify its member variables.

If the system wants to save the object state, but the object state changes little, or the object itself occupies less memory, you can use the prototype mode and the memorandum mode to implement it.

Avoid using hierarchical factory classes to create hierarchical objects, and the instance objects of the class have only one or a few combined states, it is easier to get a new instance by copying the prototype object than creating a new instance by using the constructor.

Program ape instance
Package yanbober. github. io; // implement the Cloneable interface and Override the clone method class MonkeyPrototype implements Cloneable {@ Override protected MonkeyPrototype clone () throws into {MonkeyPrototype monkeyPrototype = (MonkeyPrototype) super. clone (); return monkeyPrototype ;}// class ConcreteMonkeyPrototype extends MonkeyPrototype {public void printHasCode () {System. out. println ("ConcreteMonkeyPrototype hascode =" + this. hashCode () ;}} public class Main {public static void main (String [] args) {ConcreteMonkeyPrototype type = new ConcreteMonkeyPrototype (); type. printHasCode (); for (int index = 0; index <5; index ++) {try {ConcreteMonkeyPrototype clone = (ConcreteMonkeyPrototype) type. clone (); clone. printHasCode ();} catch (CloneNotSupportedException e) {e. printStackTrace ();}}}}

Running result:
ConcreteMonkeyPrototype hascode = 356573597
ConcreteMonkeyPrototype hascode = 1735600054
ConcreteMonkeyPrototype hascode = 21685669
ConcreteMonkeyPrototype hascode = 2133927002
ConcreteMonkeyPrototype hascode = 1836019240
ConcreteMonkeyPrototype hascode = 325040804

Notes

Copying objects in prototype mode does not call the class constructor.

Because the Object replication is completed by calling the Object class clone method, it directly copies data in the memory, so it does not call the class constructor. Not only will the code in the constructor not be executed, but even the access permission is invalid for the prototype. Do you still remember the singleton mode? In Singleton mode, you only need to set the access permission of the constructor method to private. However, the clone method directly ignores the constructor permission. Therefore,The Singleton mode conflicts with the prototype mode. Pay special attention to this mode during use.

Summary

The prototype has the following advantages:

  • When creating a new object instance is complex, you can simplify the object creation process and improve the instance creation efficiency by copying an existing instance.
  • Good scalability. The prototype provides the abstract prototype class, which can be programmed on the client.
  • The prototype mode provides a simplified creation structure. The factory method mode usually requires a factory level structure that is the same as the product class level structure, which is not required in the prototype mode, in prototype mode, product replication is implemented by cloning methods encapsulated in the prototype class, and no special factory class is required to create the product.
  • The object state can be saved by means of deep cloning, and the object state can be copied and saved in prototype mode, it can be used as needed (such as restoring to a certain historical State) to assist in undo operations.

Disadvantages of the prototype mode are as follows:

  • You need to configure a clone method for each class, And the clone method is located inside the class. When modifying the existing class, it violates the "open and closed principle ".
  • Complex code is required for deep cloning. When multiple nested references exist between objects, the classes corresponding to each layer of objects must support deep cloning.

[Craftsman if water http://blog.csdn.net/yanbober] continue to read "design patterns (Structural) Adapter Pattern" http://blog.csdn.net/yanbober/article/details/45338829

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.