Prototype of JAVA and Mode

Source: Internet
Author: User
Document directory
  •  
  • Registration Form prototype
  • Comparison of Two Forms

The Prototype mode is described as follows in Dr. Yan Hong's book JAVA and patterns:

The prototype mode belongs to the object creation mode. Specify the type of all created objects by providing a prototype object, and then create more objects of the same type by copying the prototype object. This is the purpose of the model selection.

Prototype Structure

The prototype mode requires that the object implement an interface that can "clone" itself, so that you can create a new instance by copying an instance object itself. In this way, you no longer need to care about the type of the instance when creating new objects through the prototype instance. As long as you implement the clone method, you can use this method to obtain new objects, instead, you do not need to create it through new.

The prototype has two forms: (1) Simple Form and (2) Registration Form. These two forms are only different implementations of the prototype.

Simple prototype mode

This form involves three roles:

(1) Client role: the customer class initiates a request to create an object.

(2) Prototype role: This is an abstract role, usually implemented by a Java interface or Java Abstract class. This role provides all the interfaces required for the specific prototype class.

(3) Concrete Prototype role: the object to be copied. This role must implement the interfaces required by the abstract prototype role.

Source code

Abstract prototype role

Public interface Prototype {/*** method of cloning itself * @ return a cloned Object */public Object clone ();}

Prototype role

Public class ConcretePrototype1 implements Prototype {public Prototype clone () {// The simplest clone. Create a new object. Because there is no attribute, Prototype prototype = new ConcretePrototype1 () is no longer copied (); return prototype ;}}
Public class ConcretePrototype2 implements Prototype {public Prototype clone () {// The simplest clone. Create a new object. Because there is no attribute, Prototype prototype = new ConcretePrototype2 () is no longer copied (); return prototype ;}}

Client role

Public class Client {/*** holds the required Prototype interface object */private prototype Prototype;/*** constructor, enter the required Prototype interface object */public Client (prototype Prototype) {this. prototype = prototype;} public void operation (Prototype example) {// Prototype copyPrototype = prototype. clone ();}}
Registration Form prototype

  

As the second form of prototype mode, it has an additional PrototypeManager role, which is used to create objects of a specific prototype and record each created object.

Source code

Abstract prototype role

public interface Prototype{    public Prototype clone();    public String getName();    public void setName(String name);}

Prototype role

public class ConcretePrototype1 implements Prototype {    private String name;    public Prototype clone(){        ConcretePrototype1 prototype = new ConcretePrototype1();        prototype.setName(this.name);        return prototype;    }    public String toString(){        return "Now in Prototype1 , name = " + this.name;    }    @Override    public String getName() {        return name;    }    @Override    public void setName(String name) {        this.name = name;    }}
public class ConcretePrototype2 implements Prototype {    private String name;    public Prototype clone(){        ConcretePrototype2 prototype = new ConcretePrototype2();        prototype.setName(this.name);        return prototype;    }    public String toString(){        return "Now in Prototype2 , name = " + this.name;    }    @Override    public String getName() {        return name;    }    @Override    public void setName(String name) {        this.name = name;    }}

The role of the prototype manager maintains an aggregation. As a registration of all prototype objects, this role provides the necessary methods to add new prototype objects and obtain registered prototype objects.

Public class PrototypeManager {/*** is used to record the correspondence between Prototype numbers and Prototype instances */private static Map <String, Prototype> map = new HashMap <String, prototype> ();/*** private constructor to avoid external instance creation */private PrototypeManager () {}/*** add or modify a prototype to the prototype manager * @ param prototypeId protonumber * @ param prototype instance */public synchronized static void setPrototype (String prototypeId, prototype prototype) {map. put (prototypeId, prototype);}/*** delete a prototype from the prototype manager * @ param prototypeId prototype number */public synchronized static void removePrototype (String prototypeId) {map. remove (prototypeId );} /*** obtain the prototype instance corresponding to a prototype Number * @ param prototypeId Prototype number * @ return Prototype number corresponding to the prototype instance * @ throws Exception if the instance corresponding to the prototype number does not exist, throw an Exception */public synchronized static Prototype getPrototype (String prototypeId) throws Exception {Prototype prototype = map. get (prototypeId); if (prototype = null) {throw new Exception ("the prototype you want to obtain is not registered or destroyed");} return prototype ;}}

Client role

Public class Client {public static void main (String [] args) {try {Prototype p1 = new ConcretePrototype1 (); PrototypeManager. setPrototype ("p1", p1); // obtain the Prototype to create the Prototype p3 = PrototypeManager. getPrototype ("p1 "). clone (); p3.setName ("James"); System. out. println ("first instance:" + p3); // some people dynamically switch Prototype p2 = new ConcretePrototype2 (); PrototypeManager. setPrototype ("p1", p2); // obtain the Prototype again to create Prototype p4 = PrototypeManager. getPrototype ("p1 "). clone (); p4.setName ("Li Si"); System. out. println ("second instance:" + p4); // someone canceled this PrototypeManager. removePrototype ("p1"); // obtain the Prototype again to create Prototype p5 = PrototypeManager. getPrototype ("p1 "). clone (); p5.setName ("Wang Wu"); System. out. println ("third instance:" + p5);} catch (Exception e) {e. printStackTrace ();}}}
Comparison of Two Forms

The prototype of simple form and registration form has its own strengths and weaknesses.

If the number of prototype objects to be created is small and relatively fixed, the first form can be used. In this case, the reference of the prototype object can be saved by the client.

If the number of prototype objects to be created is not fixed, the second form can be used. In this case, the client does not save the reference to the prototype object. This task is handed over to the Administrator object. Before copying a prototype object, the client can check whether the Administrator object already has a prototype object that meets the requirements. If yes, you can directly obtain this object reference from the Administrator class; if not, the client needs to copy this prototype object on its own.

 

Java cloning method

All Java classes are from java. lang. the Object class is inherited, and the Object class provides the protected Object clone () method to copy the Object. The subclass can also replace this method and provide a copy method that meets your needs. There is a basic problem in copying objects, that is, objects usually reference other objects. When you use the clone () method of the Object class to copy an Object, this Object will also be referenced by other objects.

The Cloneable interface provided by Java only plays a role, that is, to notify the Java Virtual Machine during runtime that the clone () method can be safely used in this class. You can copy an object by calling this clone () method. Because the Object class itself does not implement the Cloneable interface, if the class to be considered does not implement the Cloneable interface, the CloneNotSupportedException exception will be thrown when the clone () method is called.

Cloning Conditions

The clone () method copies an object and returns it to the caller. The meaning of the so-called "copy" and how the clone () method are implemented. Generally, the clone () method meets the following requirements:

(1) for any object x, there are: x. clone ()! = X. In other words, the cloned object is not the same as the original object.

(2) For any object x, x. clone (). getClass () = x. getClass (). In other words, the cloned object is of the same type as the original object.

(3) If the equals () method of object x is defined as appropriate, x. clone (). equals (x) should be true.

In JAVA APIs, all classes that provide the clone () method satisfy the preceding conditions. JAVA designers should abide by three conditions when designing their own clone () methods. In general, the first two of the above three conditions are required, and the third is optional.

Shortest cloning and deep cloning

  Whether you implement the cloning method by yourself or use the cloning method provided by Java, there is a problem of shortest cloning and deep cloning.

  • Shortest clone

Only responsible for cloning the data passed by value (such as the basic data type and String type), rather than copying the object it references, in other words, all references to other objects still point to the original object.

  • Deep clone

In addition to cloning the value to be cloned, the data of the reference type is also cloned. Variables that reference other objects will point to new objects that have been copied, instead of the original referenced objects. In other words, deep cloning copies all the objects referenced by the objects to be copied, and copying the referenced objects is called indirect replication.

It is difficult to determine how many layers should be deep for deep cloning. When you decide to copy an object in the form of deep cloning, you must decide whether to clone the objects indirectly or to continue using the deep cloning. Therefore, when using deep cloning, it is necessary to determine the depth. In addition, loop references may occur during the process of deep cloning, so you must be careful with the issue.

Deep cloning using serialization

The process of writing an object to a stream is a Serialization process, while the process of reading the object from the stream is called the Deserialization process. It should be noted that a copy of the object is written to the stream, and the original object still exists in JVM.

To clone an object in depth in Java, You can first implement the Serializable interface for the object, and then write the object (actually just copying the object) to a stream (serialization ), then, the object can be re-built by reading back from the stream (deserialization.

Public Object deepClone () throws IOException, ClassNotFoundException {// write the Object to ByteArrayOutputStream bos = new ByteArrayOutputStream (); ObjectOutputStream oos = new ObjectOutputStream (bos); oos. writeObject (this); // read ByteArrayInputStream bis = new ByteArrayInputStream (bos. toByteArray (); ObjectInputStream ois = new ObjectInputStream (bis); return ois. readObject ();}

The premise is that the object and all referenced objects inside the object are serializable. Otherwise, you need to carefully check whether the non-serializable objects can be set to transient, in this way, it is excluded from the replication process.

Simple cloning is obviously easier to implement than deep cloning, because all classes in the Java language will inherit a clone () method, and the clone () method is a simple clone.

Some objects, such as Thread objects or Socket objects, cannot be simply copied or shared. Whether it is simple cloning or deep cloning, as long as such indirect objects are involved, the indirect objects must be set to transient instead of being copied; or the program creates a similar object by itself, and can be used as a copy.

  

 

Sun dasheng's external spells

What if Sun dasheng's external skills are implemented using the prototype in Java? First, The Greatest Sage class assumes The customer role. Qi tianda Sheng holds an example of a zookeeper (Monkey), and a zookeeper is the original statue of the Great Sage. The Monkey class has the clone () method inherited from java. lang. Object. Therefore, you can copy a Monkey instance by calling this clone method.

Sun dasheng himself uses TheGreatestSage class representatives

Public class TheGreatestSage {
Private Monkey monkey = new Monkey ();

Public void change (){
// Clone the big sage
Monkey copyMonkey = (Monkey) monkey. clone ();
System. out. println ("the birthday of the Grand saint is:" + monkey. getBirthDate ());
System. out. println ("the birthday of the cloned dasheng is:" + monkey. getBirthDate ());
System. out. println ("is the same object as the cloned grand saint?" + (monkey = copyMonkey ));
System. out. println ("is the golden hoop held by the Grand saint the master the same object as the golden hoop held by the cloned grand saint? "+ (Monkey. getStaff () = copyMo

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.