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
To understand prototype prototyping patterns, you must first understand shallow and deep replication in Java. In some places, replication is also called cloning. Java provides both of these cloning methods. Because the Clone () method is provided in Java to implement the cloning of an object, the prototype pattern implementation suddenly becomes simple.
Shallow clone: all the variables of the cloned object contain the same value as the original object, and all of its references to other objects still point to the original object. In other words, a shallow clone simply clones the object being considered, not the object it refers to.
deep cloning: All the variables of the cloned object contain the same value as the original object, but all of its references to other objects are no longer original, and this is a pointer to a new object that has been copied. In other words, a deep copy copies all the referenced objects of the object being copied, which is called indirect replication.
Conditions that a clone must meet:
- For any object, obj, there is obj.clone ()! = obj, that is, the cloned object is not the same object as the original object.
- For any object, obj, there is Obj.clone (). GetClass () = = Obj.getclass (), that is, the Clone object is the same as the type of the original object.
- If the Equals () method of the object obj is defined appropriately, then Obj.clone (). Equals (obj) should be established.
Implementing Clone in Java () should meet the above three criteria (the first two are mandatory, the third one is recommended but not mandatory).
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.
Focus: prototype Model structure important core modules:
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.
Usage Scenarios
Creating new objects is expensive (such as initializing takes a long time, consuming too much CPU or network resources), and new objects can be obtained by copying existing objects through prototype mode, and if they are similar objects, they can be modified slightly for their member variables.
If the system wants to save the state of an object, and the state of the object changes very little, or if the object itself consumes less memory, you can use the prototype mode with the memo pattern.
To avoid using hierarchical factory classes to create hierarchical objects, and instances of classes that have only one or few combined states, it might be easier to copy a prototype object to get a new instance than to create a new instance using a constructor.
Program Ape Instance
PackageYanbober.github.io;//Implement the Cloneable interface, overriding the Clone method in the object classClass Monkeyprototype implements Cloneable {@Override protectedMonkeyprototypeClone()throwsclonenotsupportedexception {Monkeyprototype Monkeyprototype = (monkeyprototype)Super. Clone ();returnMonkeyprototype; }}//prototype pattern implementation classClass Concretemonkeyprototype extends Monkeyprototype { Public void Printhascode() {System.out.println ("Concretemonkeyprototype hascode="+ This. Hashcode ()); }} Public class Main { Public Static void Main(string[] args) {Concretemonkeyprototype type =NewConcretemonkeyprototype (); Type.printhascode (); for(intindex=0; index<5; index++) {Try{Concretemonkeyprototype clone = (Concretemonkeyprototype) type.clone (); Clone.printhascode (); }Catch(Clonenotsupportedexception e) {E.printstacktrace (); } } }}
Operation Result:
Concretemonkeyprototype hascode=356573597
Concretemonkeyprototype hascode=1735600054
Concretemonkeyprototype hascode=21685669
Concretemonkeyprototype hascode=2133927002
Concretemonkeyprototype hascode=1836019240
Concretemonkeyprototype hascode=325040804
Precautions
Copying an object using prototype mode does not invoke the constructor 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.
sum up a
The prototype model has the following advantages:
- When creating a new object instance is more complex, you can simplify the object creation process by replicating an existing instance to increase the efficiency of the creation of the instance.
- Extensibility is good, and the prototype schema provides an abstract prototype class that can be programmed on the client for abstract prototype classes.
- Prototype mode provides a simplified creation structure, and the factory method pattern often requires a factory hierarchy with the same level structure as the product class, which is not required in prototype mode, and the replication of the product in prototype mode is achieved through a cloning method encapsulated in the prototype class, without the need for a dedicated factory class to create the product.
- 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, which is inside a class that violates the "open and closed principle" when the existing class is reformed.
- When implementing deep clones, you need to write more complex code, and when there are multiple nested references between objects, in order to achieve deep cloning, the classes corresponding to each layer of objects must support deep cloning is more troublesome.
Prototype pattern (Prototype pattern) for design mode (create type)