Introduction and use of the prototype design mode, and introduction of the prototype design mode

Source: Internet
Author: User

Introduction and use of the prototype design mode, and introduction of the prototype design mode
Introduction

Prototype Pattern is used to create duplicate objects while ensuring performance. This type of design mode belongs to the creation mode, which provides an optimal way to create objects.

This mode implements a prototype interface that is used to create a clone of the current object. This mode is used when the cost of directly creating an object is large. For example, an object needs to be created after a high-cost database operation. We can cache this object, return its clone in the next request, and update the database as needed to reduce database calls.

Intention: Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.

Main Solution: Create and delete prototypes at runtime.

When to use1. When a system should be independent of its product creation, composition, and representation. 2. When the class to be instantiated is specified at the runtime, for example, through dynamic loading. 3. To avoid creating a factory class level parallel to the product class level. 4. When an instance of a class can only have one of several combinations of different States. Creating prototype and cloning them may be more convenient than manually instantiating this type with the appropriate state each time.

Solution: Use an existing prototype object to quickly generate instances that are the same as the prototype object.

Key code: 1. Implement the clone operation, inherit Cloneable in JAVA, rewrite clone (), and. NET, you can use the MemberwiseClone () method of the Object class to implement the shortest copy of an Object or the deep copy through serialization. 2. The prototype mode is also used to isolate the coupling between the user of the class object and the specific type (variable type). It also requires that these "variable classes" have stable interfaces.

Application Instance: 1. cell division. 2. The Object clone () method in JAVA.

Advantages: 1. Improved performance. 2. Escape the constructor constraints.

Disadvantages: 1. The function of the class should be considered comprehensively when the cloning method is configured. This is not difficult for the new class, but not necessarily easy for the existing class, especially when a class reference does not support serialized indirect objects, or references contain cyclic structures. 2. The Cloneable interface must be implemented. 3. Escape the constructor constraints.

Use Cases: 1. Resource Optimization scenarios. 2. class initialization consumes a lot of resources, including data and hardware resources. 3. Performance and security requirements. 4. The prototype mode can be used to generate an object through new, which requires tedious data preparation or access permissions. 5. Multiple modifier scenarios of an object. 6. When an object needs to be provided to other objects for access and each caller may need to modify its value, you can consider copying multiple objects in prototype mode for the caller to use. 7. In actual projects, the prototype mode rarely appears independently. It usually appears together with the factory method mode. Create an object by using the clone method and then provide the factory method to the caller. The prototype has been integrated with Java and can be easily used.

Notes: Unlike constructing a new object by instantiating a class, the prototype mode generates a new object by copying an existing object. The implementation of Cloneable and rewrite in the light copy mode. The deep copy mode reads binary streams through Serializable.

UML diagram:

Specific implementation:

The prototype mode is a widely used design mode, and Clone is also 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.

Let's take an example to illustrate the specific implementation and functions of the prototype model. Consider a scenario where you want to write a resume, including the name, gender, age, family members, and work experience. The current requirement is that you need to deliver the created resume to multiple companies. Therefore, after creating a created object, you must be able to copy the created resume. At this time, several other students also want to find a job. For convenience, they used the created files as templates and made some modifications based on their own situation.

To meet the above requirements, we first define a work experience class, which contains two member variables: work time and company name.

public class WorkExperience {    public String timeArea = null;      public String company = null;  }

Next, define a resume class, which is equivalent to the entity prototype class in the UML diagram. As for the image prototype class or interface, we have provided the Cloneable interface in Java, therefore, we only need to implement it. First, let's look at an implementation method.

Public class Resume implements Cloneable {public String name = null; public Integer age = null; public String sex = null; public ArrayList
 
  
FamMem = new ArrayList
  
   
(); Public WorkExperience work = null; public Resume (String name) {this. name = name; work = new WorkExperience () ;}// Resume public Resume (String string, ArrayList
   
    
FamMem) {this. famMem = famMem; this. name = string; work = new WorkExperience ();} public void setName (String name) {this. name = name;} // setName public void setPersonal (String sex, int age, ArrayList
    
     
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/*** repeat the clone () method to the public type and call 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 public void setPersonal (String sex, int age) {this. sex = sex; this. age = age ;}}
    
   
  
 

The following is the client code:

Public class PrototypeDemo {public static void main (String [] args) throws CloneNotSupportedException {ArrayList
 
  
FamMem = new ArrayList
  
   
(); // Family member list famMem. add ("Papa"); famMem. add ("Mama"); // create initial Resume resume1 = new Resume ("Jobs", famMem); resume1.setPersonal ("Male", 26 ); resume1.setWork ("2013/8/1-2015/6/30", "Huawei"); // copy Resume 2 from Resume 1 and modify Resume resume2 = resume1.clone () for family members and work experience (); resume2.setName ("Tom"); resume2.famMem. add ("Brother"); resume2.setWork ("2015/7/1-2016/6/30", "Baidu"); resume1.display (); resume2.display ();} // main}
  
 

Running result:

According to the running results, although Tom successfully copied the resume of Jobs, the subsequent modifications to the Tom family members and work experience resulted in the simultaneous modification of the resume of Jobs, this is because we directly call the local clone () method of the Object class when implementing the clone () method, because the clone () method of the Object executes the shortest copy, therefore, the famMem and work fields in Jobs and Tom both point to the same object instance. To implement deep copy, you must modify the clone () method.

@Override    public Resume clone() throws CloneNotSupportedException {        int age = this.age;        String sex = this.sex;        String name = new String(this.name);        ArrayList
 
   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  
  
 

Running result:

It can be seen that after the clone () method has the deep copy function, the established copy is independent of the original resume.

The above uses the prototype class to implement the Cloneable interface to implement the prototype mode. You can also customize the prototype class and declare an interface to clone itself to implement the above operations:

A prototype class that declares an interface for cloning itself
public interface Prototype {    Prototype cloneResume();}

-Work Experience

public class WorkExperience {    public String timeArea = null;      public String company = null;  }
Specific prototype to clone itself
Public class Resume implements Prototype {public String name = null; public Integer age = null; public String sex = null; public ArrayList
 
  
FamMem = new ArrayList
  
   
(); Public WorkExperience work = null; public Resume (String name) {this. name = name; work = new WorkExperience () ;}// Resume public Resume (String string, ArrayList
   
    
FamMem) {this. famMem = famMem; this. name = string; work = new WorkExperience ();} public void setName (String name) {this. name = name;} // setName public void setPersonal (String sex, int age, ArrayList
    
     
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 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 public void setPersonal (String sex, int age) {this. sex = sex; this. age = age;} // a Prototype class to clone itself. @ Overridepublic Prototype cloneResume () {Resume resume = new Resume (this. name); ArrayList
     
      
FamMem = new ArrayList
      
        (This. famMem); resume. setWork (work. timeArea, work. company); resume. setPersonal (sex, age, famMem); return resume ;}}
      
     
    
   
  
 

In fact, deep/shallow copy is mainly used to copy the objects contained in the current class during the object copy process. Otherwise, it is used as a deep copy.

Summary:

The prototype mode is the simplest of all design patterns. It does not have a complex inheritance system. You only need to implement the Cloneable interface and rewrite the clone () method for classes that require the copy function. However, it is widely used. It encapsulates the copy operations on each field (private or common) in an object in the clone () method. In this way, if you use this class, you do not need to understand the details of each field in the object. You can directly call the clone () method to copy the object () you can also set the copy permission for different fields, so that only the fields that can be copied.

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.