[Design mode] prototype mode

Source: Internet
Author: User
Introduction

The ancients cloud: books cannot be read without being borrowed.

Now it books are updated fast, expensive, and quality levels are even more uneven. I cannot bear to see that books bought with hard-earned money will be eliminated in less than half a year.

We do not want to support translators who use modern tools such as Kingsoft fast translation and word overlord.

So I went to the bookstore to run a debit card, so that I had no worries. I can change the books if they are not good!

However, it is also uncomfortable to borrow books, that is, to see useful or important information. You cannot mark it next to the book.

This page is usually copied, so that you can draw and save it as your own things.

In software design, similar or similar problems often occur. gof calls this solution a prototype.

Maybe the original model will give you some new inspiration.

Definition and Structure

The prototype mode belongs to the object creation mode, and the gof defines it:Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object.

The clone () method is provided in Java to clone objects. Therefore, prototype implementation is much simpler.

What is the difference between creating an object using the clone method and the factory mode used to create an object?

As mentioned above, the factory model has weak adaptability to new products: when creating a new product, you must modify or add a factory role.

In addition, an additional factory object must be created to create a product object. What will it look like to create an object in the prototype mode?

Prototype Structure
  1. Customer role: let a prototype clone itself to get a new object.
  2. Abstract prototype role: implements its own clone method. The class playing this role is usually an abstract class, and it has many concrete sub-classes.
  3. Prototype role: the Copied object, which is a subclass of the abstract prototype role.

First, create a class chart.

  

According to the definition, the customer role is not only responsible for using objects, but also for generating and cloning object prototypes.

In this way, the division of customer roles is not very clear, so we put out the object prototype generation and cloning function orders into onePrototype Manager.

The prototype manager maintains the list of existing prototypes. When using the prototype manager, the customer sends a request to the prototype manager and can modify the inventory maintained by the prototype manager.

In this way, the customer can implement system expansion without coding.

Class chart Representation

Analysis

For abstract prototype roles and specific prototype roles, they are an inheritance or implementation relationship. There is no fun. Remember to implement the clone method.

So how do customers use these role objects?

The simplest method is:

// First create a prototype role as the sample prototype P = new concreteprototype ();...... // Use prototype P to clone a new object P1 prototype p1 = (prototype) p. Clone ();
View code

Of course, this is just a simple expression of the operating process of the prototype mode.

In practice, a prototype manager usually exists between the client program and the prototype role (see the following example ).

ThereforeCreate a prototype role and copy a prototype role to separate it from the customer program..

Then we can truly appreciate the effects of the prototype.

// After the prototype manager is used, the customer obtains the object prototype p1 = prototypemanager. getmanager (). getprototype ("concreteprototype ");
View code

 

The implementation of the prototype manager mentioned above is simply the maintenance of the prototype list.

Consider the following:

  1. To save a prototype object list, we can use a hashmap to make the prototype object correspond to its name;
  2. The prototype manager only needs one, so you can use the singleton mode to implement control;
  3. The function of obtaining, registering, and deleting a prototype object is only related to hashmap.
1 class prototypemanager {2 Private Static prototypemanager PM; 3 private map prototypes = NULL; 4 private prototypemanager () {5 prototypes = new hashmap (); 6} 7 8 // use Singleton mode to obtain the unique instance 9 public static prototypemanager getmanager () {10 if (PM = NULL) of the prototype manager) {11 pm = new prototypemanager (); 12} 13 return PM; 14} 15 public void register (string name, object prototype) {16 prototypes. put (name, prototype); 17} 18 Pu BLIC void unregister (string name) {19 prototypes. remove (name); 20} 21 public prototype getprototype (string name) {22 if (prototypes. containskey (name) {23 // returns the copy of the prototype in the list to the customer 24 return (prototype) prototypes. get (name )). clone (); 25} else {26 prototype object = NULL; 27 try {28 object = (prototype) class. forname (name ). newinstance (); 29 register (name, object); 30} catch (exception e) {31 system. err . Println ("class" + name + "not defined! "); 32} 33 return object; 34...
View code

In this way, when a customer customizes a new product object, a prototype object is also registered with the prototype manager, the class used only needs to get an object from the prototype manager according to the customer's needs.

This makes function expansion easier.

  The prototype mode has the same characteristics as other creation modes: They all encapsulate the creation process of a specific product, so that the customer is unaware of the Creation.

As in the preceding example, a client program only knows an abstract product interface.

Of course, it also hasExtraordinary:

  1. By adding or deleting objects registered in the prototype manager, you can add or delete products at runtime more conveniently than other creation modes.
  2. If an object is always created by combining several fixed components in different ways;
  3. If only the instance attributes of objects are different.
  4. Cache objects in different situations and clone and use them directly.
  5. Perhaps this is faster than using the passed parameter to re-create an object.

You may have discoveredThe prototype model is closely related to the factory model.:

  1. The prototype manager is not a factory.
  2. Of course, this factory has been improved (for example, the above example uses the reflection mechanism of Java), removing subclasses that are as diverse as the abstract factory mode or factory method mode.
  3. Therefore, the prototype mode adds the clone method based on the factory mode.

Maybe you can't tell meWhat is the difference between using the clone method to generate an object and a new object?

  1. In prototype mode, clone can dynamically extract the status of the current object during running and clone it to a new object. Then, the new object can be operated without damaging the original object;
  2. New can only get one initialized object, but in actual applications, this is often not enough.
  3. Especially when your system requires good scalability, it is also necessary to use the prototype in the design.
  4. For example, your system allows customers to customize their desired categories, but the initialization of such categories may need to pass more parameters than existing categories, this makes the class that uses it do not know how to initialize it (because it has been written down), unless the class is modified.
  5. We can see that the clone method cannot be replaced by constructors.

I have analyzed so much. For exampleTypical examples of Prototype:

The performance appraisal software should conduct annual analysis on various appraisal data for this year, which is stored in the database.

Generally, we encapsulate this group of data in a class, and then pass an instance of this class as a parameter to the Analysis Algorithm for analysis, the analysis result is returned to the corresponding variables in the class.

Suppose we decided to make another analysis for this set of data to compare and evaluate the analysis results.

At this time, the clone of classes containing this set of data is much better than the data obtained by connecting to the database again.

Any mode is defective.

Main prototypeThe defect is that each prototype must contain the clone method.It is difficult to add clone operations on the basis of existing classes;

In addition, it is more difficult to implement some objects that do not support copy or circular reference.

Summary

Because the clone method has some drawbacks and risks in Java implementation, it is not recommended to use the clone method.

Therefore, the usage of the prototype is rarely seen in Java applications.

However, the prototype can give us some inspiration.

 

@ Cheng Peng Zhiyuan

(Blogs: lcw.cnblogs.com)

(Email:[Email protected])

(Qq:552158509)

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.