Prototype pattern (Prototype pattern) for design mode (create type)

Source: Internet
Author: User

PS One sentence: Eventually choose Csdn to organize the publication of the knowledge points of these years, the article parallel migration to CSDN. Because CSDN also support markdown grammar, Ah!

Overview

Prototype mode is a creation design pattern that returns a new instance by copying an already existing instance, rather than creating a new instance. The copied instance is what we call a prototype, which is customizable. Prototype patterns are used to create complex or time-consuming instances, because in this case, copying an already existing instance can make the program run more efficiently, or create values equal, but with a different naming of similar data.

The prototype pattern requires that an object implement an interface that can "clone" itself, so that a new instance can be created by copying an instance object itself. Thus, by creating a new object from the prototype instance, it is no longer necessary to care about the type of the instance itself, so long as the method of cloning itself is implemented, it is possible to acquire new objects through this method without having to create them through new.

Core

Concept: use prototype instances to specify the kind of objects that are created, and create new objects by copying those prototypes. Prototype mode is an object-creation pattern.

Forms of Expression classification:

    • Simple Form
    • form of registration

The two forms of expression are just different from the implementation of the prototype pattern.

Key points:

Simple form of prototype model structure important core modules:

(client) Customer role

The client class presents a request to create an object.

(Prototype) Abstract prototype role

This is an abstract role, usually implemented by a Java interface or Java abstract class. This role gives the interfaces required for all the specific prototype classes.

(concrete Prototype) specific prototype role

The object that is being copied, this role needs to implement the interface required by the abstract prototype role.

(Prototypemanager) prototype Manager role

The role is to create objects of a specific prototype class and record each object that is created.

The prototype model structure of the registration form is an important core module:

(client) Customer role

The client class presents a request to create an object.

(Prototype) Abstract prototype role

This is an abstract role, usually implemented by a Java interface or Java abstract class. This role gives the interfaces required for all the specific prototype classes.

(concrete Prototype) specific prototype role

The object that is being copied, this role needs to implement the interface required by the abstract prototype role.

(Prototypemanager) prototype Manager role

The role is to create objects of a specific prototype class and record each object that is created.

Usage Scenarios

Resource optimization scenario, class initialization needs to digest a lot of resources, this resource includes data, hardware resources and so on.

Performance and security requirements scenarios where creating an object with new requires very tedious data preparation or access permissions, you can use prototype mode.

A scenario in which an object has multiple modifiers, an object needs to be provided to other object access, and each caller may need to modify its value, consider copying multiple objects using prototype mode for the caller to use.

In real-world projects, prototype patterns rarely appear alone, typically in conjunction with the factory method pattern, creating an object by using clone, which is then provided by the factory method to the caller. Prototype mode has been seamless with Java, you can pinch.

Program Ape Instance

The basic example of a simple form of prototype pattern , the following code strictly according to the simple form of the prototype model of the three elements of the implementation, is a fundamental structure of the expression.

 PackageYanbober.github.io;//Abstract prototype roleInterface Iprototype {Object clones ();}//Specific prototype roleClass Concreteprototypelowimpl implements Iprototype {@Override     PublicObjectclones() {Iprototype Iprototype =NewConcreteprototypelowimpl ();returnIprototype; }}class Concreteprototypehighimpl implements Iprototype {@Override     PublicObjectclones() {Iprototype Iprototype =NewConcreteprototypehighimpl ();returnIprototype; }}//Client role Public  class Main {     Public Static void Main(string[] args) {Iprototype Iprototype =NewConcreteprototypelowimpl (); for(intindex=0; index< -;        index++) {Concreteprototypelowimpl clone = (Concreteprototypelowimpl) iprototype.clones (); } Iprototype =NewConcreteprototypehighimpl (); for(intindex=0; index< -;        index++) {Concreteprototypehighimpl clone = (Concreteprototypehighimpl) iprototype.clones (); }    }}


The basic example of the prototype pattern in the form of registration, the following code is implemented strictly according to the four elements of the prototype pattern of the above registration form, is a fundamental structure expression.

 PackageYanbober.github.io;ImportJava.util.HashMap;ImportJava.util.Map;//Abstract prototype roleInterface Iprototype {Object clones ();voidSettemp (String temp); String gettemp ();voidPrint ();}//Specific prototype roleClass Concreteprototypelowimpl implements Iprototype {PrivateString mtemp;@Override     PublicObjectclones() {Iprototype Iprototype =NewConcreteprototypelowimpl (); Iprototype.settemp (mtemp);returnIprototype; }@Override     Public void settemp(String temp) { This. mtemp = temp; }@Override     PublicStringgettemp() {return  This. mtemp; }@Override     Public void Print() {System.out.println ("concreteprototypelowimpl#"+ This. Hashcode () +"# temp="+ This. mtemp); }}class Concreteprototypehighimpl implements Iprototype {PrivateString mtemp;@Override     PublicObjectclones() {Iprototype Iprototype =NewConcreteprototypehighimpl (); Iprototype.settemp (mtemp);returnIprototype; }@Override     Public void settemp(String temp) { This. mtemp = temp; }@Override     PublicStringgettemp() {return  This. mtemp; }@Override     Public void Print() {System.out.println ("concreteprototypehighimpl#"+ This. Hashcode () +"# temp="+ This. mtemp); }}//Prototype Manager roleClass Prototypemanager {Private Staticmap<string, iprototype> keymap =NewHashmap<> ();Private Prototypemanager() {//null} Public synchronized Static void Setprototype(String key, Iprototype value)    {Keymap.put (key, value); } Public synchronized StaticIprototypeGetprototype(String key) {Iprototype Iprototype = Keymap.get (key);if(Iprototype = =NULL) {Throw NewIllegalArgumentException ("Can ' t find your key in the manager map!"); }returnIprototype; } Public synchronized Static void Removeprototype(String key)    {Keymap.remove (key); }}//Client role Public  class Main {     Public Static void Main(string[] args) {Iprototype Iprototype =NewConcreteprototypelowimpl ();        Iprototype.print (); Prototypemanager.setprototype ("Iprototype", Iprototype); Iprototype clone = (iprototype) prototypemanager.getprototype ("Iprototype"). clones (); Clone.settemp ("Clone Step 1!");        Clone.print (); Iprototype =NewConcreteprototypehighimpl ();        Iprototype.print (); Prototypemanager.setprototype ("Iprototype", Iprototype); Clone = (Iprototype) prototypemanager.getprototype ("Iprototype"). clones (); Clone.settemp ("Clone step 2!");        Clone.print (); Prototypemanager.removeprototype ("Iprototype"); }}

The results of the operation are as follows:
concreteprototypelowimpl#1163157884# Temp=null
concreteprototypelowimpl#1956725890# temp=clone Step 1!
concreteprototypehighimpl#356573597# Temp=null
concreteprototypehighimpl#1735600054# Temp=clone Step 2!

Code Reflection: The Simple form and the registration form of the prototype model each has its strengths and weaknesses. If you need to create a small number of prototype objects and are relatively fixed, you can take the first form. In this case, the reference to the prototype object can be saved by the client itself. If the number of prototype objects you want to create is not fixed, you can take a second form. In this case, the client does not save a reference to the prototype object, and the task is given to the Administrator object. Before copying a prototype object, the client can see if the Administrator object already has a prototype object that meets the requirements. If so, the object reference can be obtained directly from the Administrator class, and if not, the client needs to replicate the prototype object on its own.

prototype patterns available in Java

The protected object Clone () method of the object class

The Java object class provides the protected object clone () method for copying objects, which of course can also displace this method, providing a copy method that satisfies its needs. The basic problem with object replication is that objects typically have references to other objects. When you use the Clone () method of the object class to copy an object, the object's references to other objects are also copied.

Cloneable interface

The Cloneable interface provided by the Java language serves only one function, which is to inform the Java Virtual machine at runtime that it can safely use the Clone () method on this class. You can get a copy of an object by calling this clone () method. Because the object class itself does not implement the Cloneable interface, calling the Clone () method throws a Clonenotsupportedexception exception if the class being considered does not implement the Cloneable interface.

Basic conditions for cloning to be met in Java

The Clone () method copies a copy of the object and returns it to the caller, so the Clone () method needs to meet the following description:

    • For any object, OBJ, there are: Obj.clone ()!=obj. In other words, a cloned object is not the same object as the original object.

    • For any object, OBJ, there are: Obj.clone (). GetClass () = = Obj.getclass (), in other words, the Clone object is the same as the type of the original object.

    • If the Equals () method of the object OBJ defines its proper words, then obj.clone (). Equals (OBJ) should be established.

In the Java language API, all classes that provide the clone () method satisfy these conditions. The Java language designer should also abide by three conditions when designing his own clone () method. In general, the first two of the three conditions above are required, and the third one is optional.

Shallow cloning and deep cloning of Java

Whether you are implementing the cloning method yourself or using the cloning method provided by Java, there is a problem of shallow cloning and deep cloning.

Superficial cloning

It is only responsible for cloning data that is passed by value (such as the base data type and a special string type) without duplicating the object it refers to, in other words, all references to other objects still point to the original object.

Deep cloning

In addition to a shallow clone of the value to be cloned, it is also responsible for cloning the reference type's data. Variables that refer to other objects will point to new objects that have been copied, not those that are already referenced. In other words, a deep clone copies the objects referenced by the object being copied, and this copy of the referenced object is called an indirect copy.

Depth cloning to how many layers, is a difficult to determine the problem. When you decide to copy an object in a deep clone, you must decide whether to take a shallow clone or continue to use deep cloning for objects that are indirectly copied. Therefore, in the case of deep cloning, we need to decide how deep it is to be deep. In addition, in the process of deep cloning, it is very likely that the problem of circular references, must be handled with care.

Precautions

A prototype schema that is implemented using the Java API does not invoke the constructor method of the class. Because object replication is done by invoking the Clone method of the object class, it replicates the data directly in memory and therefore does not invoke the constructor of the class. Not only does the code in the construction method not execute, but even access permissions are not valid for the prototype mode. Do you remember the singleton mode? In singleton mode, a singleton can be implemented as long as the access permission of the construction method is set to private type. However, the Clone method directly ignores the permissions of the constructor method, so the singleton mode is conflicting with the prototype mode and should be paid special attention when used.

prototype pattern design using templates provided by Java

There are two main points to using the Java-provided API to prototype prototypes of the prototype classes:

Implementing the Cloneable Interface

In the Java language, there is a cloneable interface, which only works by notifying the virtual machine at runtime that it can safely use the Clone method on classes that implement this interface. In a Java virtual machine, only classes that implement this interface can be copied, or clonenotsupportedexception exceptions will be thrown at run time.

Overriding the Clone method in the object class

In Java, the parent class of all classes is the object class, and the object class has a Clone method that returns a copy of the object, but its scope is protected type, and the generic class cannot be called, so The prototype class needs to modify the scope of the Clone method to the public type.

Code to combat a

The following is a prototype pattern implemented using Java's API, not many explanations:

 PackageYanbober.github.io;class Iprototype implements Cloneable { PublicIprototypeClone() {Iprototype prototype =NULL;Try{prototype = (Iprototype)Super. Clone (); }Catch(Clonenotsupportedexception e)        {E.printstacktrace (); }returnPrototype }}class Concreteprototypeimpl extends iprototype{ Public void Print() {System.out.println ("I ' m Impl!!!"); }} Public  class Main {     Public Static void Main(string[] args) {Concreteprototypeimpl CP =NewConcreteprototypeimpl (); for(intI=0; i< -;            i++) {Concreteprototypeimpl CLONECP = (Concreteprototypeimpl) cp.clone ();        Clonecp.print (); }    }}
sum up a

The prototype model has the following advantages:

    • When creating a new object instance, using prototype mode simplifies the creation of the object, and by replicating an existing instance, you can increase the efficiency of the new instance creation.
    • Extensibility is good, abstract prototype classes are provided in prototype mode, and the client can program on abstract prototype classes.
    • You can save the state of an object using a deep clone, use prototype mode to copy an object and save its state so that it can be used when needed (such as reverting to a historical state) to assist in the undo operation.

The prototype pattern disadvantages are as follows:

    • Each class needs to be equipped with a clone method, and the Clone method is inside a class, and when the existing class is reformed, the source code needs to be modified, which violates the "open and closed principle".
    • When implementing deep clones, you need to write more complex code, and when there are multiple nested references between objects, in order to implement deep cloning, the classes corresponding to each layer of objects must support deep cloning, which can be cumbersome to implement.

Prototype pattern (Prototype pattern) for design mode (create type)

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.