Java design Pattern (v) detailed prototype mode __java

Source: Internet
Author: User
Tags shallow copy
first, the introduction

During the development process, sometimes you encounter situations where multiple instances are created for a class, where the internal members are often identical or slightly different, and the instance is expensive to create or requires more input, and if you can duplicate a created object instance repeatedly to create multiple identical objects, This can greatly reduce the overhead of creating objects, which requires prototyping patterns.


Second, the mode of detailed


1. Mode Analysis

The prototype pattern can be used to determine the type of object that is created by an object instance, and to create a new instance by copying it. In total, the prototype pattern is actually creating another new object from one object, so that the new object has the characteristics of the original object.

Figure 1 shows a UML diagram of the prototype pattern, which shows that the structure of the prototype pattern is very simple. First, all classes that can be prototypes should have a method clone () that is used to replicate itself. So, we can abstract out an abstract prototype class or interface, which has only one clone (), and all the concrete prototype classes implement the method and define the specific behavior of replicating itself. A clone method that invokes a specific prototype object in the client can replicate the prototype object into a new object.


Figure 1 Prototype Model UML Diagram 2, concrete implementation

The prototype pattern is an application and its extensive design pattern, and clone is a very common operation, so that in Java, the ultimate parent class object uses the Clone method as the basic function of all classes. And Java also provides the Cloneable interface (for details on the cloneable interface, please see my other blog post: javase learning Essay (a) Cloneable interface source code Analysis and technical details), which facilitates the implementation of the prototype model.

We also use an example to illustrate the concrete implementation and role of the prototype model. Consider a resume-writing scenario where the information included includes names, gender, age, family members, and work experience. The current requirement is that a resume is required to be delivered to multiple companies, so the child creates an object and requires the ability to replicate the created resume. At this time, there are several other students also want to find a job, in order to facilitate, it has been created as a template, and then according to their own situation made some changes.

To achieve these requirements, we first define a working experience class with two member variables for working hours and company names.

Class Workexperience {public
    
    String timearea = null;
    Public String company = null;
       
} /*workexperience*/

Then define a resume class, this class is equivalent to an entity prototype class in a UML diagram, as in the case of a prototype class or interface, in Java I have already provided the Cloneable interface, so we just need to implement it (the implementation of the method can be viewed through the link given above to my other posting view, Here I directly give the implementation of the interface, we first look at a way to implement.

Class Resume implements cloneable {public String name = NULL;
    Public Integer age = null;
    public String sex = null;
    Public arraylist<string> Fammem = new arraylist<> ();
    
    Public workexperience work = null;
        Public Resume (String name) {this.name = name;
    Work = new Workexperience ();
    }//Resume public void SetName (String name) {this.name = name; }//setname public void setpersonal (String sex, int age, arraylist<string> fammem) {This.age = age
        ;
        This.sex = sex;
    This.fammem = Fammem;
        }//setpersonal public void Setwork (String timearea, String company) {Work.timearea = Timearea;
    Work.company = Company;
     }//setwork/** * Heavier the Clone () method is the public type and calls the local clone () method of the object class. 
    * * @Override public Resume Clone () throws Clonenotsupportedexception {return (Resume) Super.clone (); }//clone public void DisplaY () {System.out.println (THIS.name + "" + This.sex + "" + this.age);
        System.out.print ("Family Member:");
        for (String Elem:fammem) System.out.print (Elem + "");
        System.out.println ();
        System.out.print ("Work Experience:" + This.work.timeArea);
    System.out.println ("" + This.work.company); }//Display}/*resume*/

Next is the client code:

public class Prototypedemo {public

    static void Main (string[] args) throws Clonenotsupportedexception {
        arraylist<string> Fammem = new arraylist<> (); Family members List
        fammem.add ("Papa");
        Fammem.add ("Mama");
        
        Create an initial resume
        Resume resume1 = new Resume ("Jobs", Fammem);
        Resume1.setpersonal ("Male", num);
        Resume1.setwork ("2013/8/1-2015/6/30", "the");
        
        Copy resume 2 through CV 1, and modify family members and work experience
        Resume resume2 = Resume1.clone ();
        Resume2.setname ("Tom");
        Resume2.famMem.add ("Brother");
        Resume2.setwork ("2015/7/1-2016/6/30", "Baidu");
        
        Resume1.display ();
        Resume2.display ();
    } Main
    
}/*pritotype*/

Run Result:


From the results of the operation, although Tom succeeded in duplicating Jobs ' resume, the subsequent revisions to Tom's family and working experience led to the simultaneous revision of Jobs ' resume, which was caused by the direct invocation of the native Clone () method of the object class when implementing the Clone () method. Because the object's clone () method performs a shallow copy, both the Fammem and work fields in jobs and Tom's resumes point to the same object instance. To achieve deep copy, you must modify the Clone () method (see: Javase Learning Essay (i) Cloneable interface source analysis and technical details):

Class Resume implements cloneable {public String name = NULL;
    public int age = 0;
    public String sex = null;
    Public arraylist<string> Fammem = new arraylist<> ();
    
    Public workexperience work = null;
        Public Resume (String name, arraylist<string> fammem) {this.name = name;
        This.fammem = Fammem;
    Work = new Workexperience ();
    }//Resume public void SetName (String name) {this.name = name;
        }//setname public void setpersonal (String sex, int age) {this.age = age;
    This.sex = sex;
        }//setpersonal public void Setwork (String timearea, String company) {Work.timearea = Timearea;
    Work.company = Company;
     }//setwork/** * Heavier the Clone () method is the public type, creates a new object for each field, and implements the deep copy feature.
        * * @Override public Resume Clone () throws clonenotsupportedexception {int age = This.age;
        String sex = this.sex; String name = new STRING (this.name);
        
        arraylist<string> Fammem = new arraylist<> (THIS.FAMMEM); 
        Resume copy = new Resume (name, FAMMEM);
        Copy.setpersonal (sex, age);
        Copy.setwork (This.work.timeArea, This.work.company);
    return copy;
        }//clone public void display () {System.out.println (THIS.name + "" + This.sex + "" + this.age);
        System.out.print ("Family Member:");
        for (String Elem:fammem) System.out.print (Elem + "");
        System.out.println ();
        System.out.print ("Work Experience:" + This.work.timeArea);
    System.out.println ("" + This.work.company); }//Display}/*resume*/

Run Result:

As can be seen, the Clone () method with deep copy function, after the establishment of replication and the original resume is independent.


Third, summary


The prototype model can be said to be the simplest of all design patterns, it does not have a complex inheritance system, just need to make the class with copy function implement Cloneable interface and rewrite the Clone () method. However, it is widely used and is encapsulated in the Clone () method for copying operations of each field (whether private or common) in an object. This way, users who use the class do not need to understand the details of each field in the object, and call the Clone () method directly to implement the object's copy , and the Clone () method allows you to set replicated permissions for different fields, allowing replication only for fields that can be replicated.

Related Article

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.