Prototype, not just clone

Source: Internet
Author: User

The intention of the prototype model is often misunderstood as a copy object. Originally, I felt that the design model was completely unnecessary (and did not dare) to write any articles. The GoF book was clearly and accurately written, and there were countless examples, however, I have seen countless articles that have completely transformed the prototype into a new object from an existing object, so I decided to write an article in the vernacular, you are welcome to shoot bricks, shoot, shoot, and shoot in the dead ......

Before I talk nonsense, I still copy GoF first, with the intention:

Use a prototype instance to specify the types of objects to be created, and copy these prototype objects to create new objects.

What do you mean? I think we should remove the adjectives in this phrase:Specify a category and create an object.This makes it easy to understand more. The intention of this mode is not to copy an identical object, but to create an object and specify its type with a prototype. Copying is just a method, not the purpose.

This motivation is not copied. It is actually a clear example, but the music editor seems to be a little farther away from our programmer's life.

This applicability is more practical. Copy the following:

When a system should be independent from its product creation, composition, and representation, the Prototype mode should be used; and
• When the class to be instantiated is specified at the runtime, for example, through dynamic loading; or
• To avoid creating a factory class level parallel to the product class level; or
• 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.

The Prototype mode is the most widely used scenario in the Prototype mode. A system is actually a layer of classes, modules, libraries, or multi-layer architectures written by a programmer. When you try to write a system that fully complies with the DIP, you may not be able to avoid creating new objects that comply with specific interfaces, but because the DIP principle does not allow you to depend on specific types, it is impossible to determine which specific class to create. At this time, the prototype provides a very clever way: "I want to create an object of the same type as it!"

The following three examples represent three scenarios: "When the class to be instantiated is scheduled at runtime, for example, by dynamically loading", this scenario dynamically specifies the type of the object to be created, the object you want to create may be related to user input or other runtime information, if you don't want to write a group of if else or switch in every place where you create an object, prototype is a good choice.

"To avoid creating a factory-class hierarchy that is parallel to the product-class hierarchy", this is the prototype mode that replaces the abstract factory. In fact, the prototype mode regards the object as a factory.

"When an instance of a class can only have one of several combinations of different States. Creating prototype numbers and cloning them may be more convenient than manually instantiating them with the appropriate state each time .", This sentence is a little complicated. In fact, it is also a very corner scenario. Some Classes belong to a limited number of objects. For example, although snooker has different colors, but red, yellow, green, brown, Blue, pink and black, and white, you cannot create a purple ball. At this time, we can create objects in the prototype mode. First, we manually instantiate one ball of the eight colors, and then create all the objects in the copy mode.

The next result is from someone else's copy (original http://blog.csdn.net/coolstar/archive/2001/08/16/5772.aspx ):

P r o t y p e has many and Abstract Factory (3. 1) and B u I l d e r (3. 2) the same effect: it hides a specific product class from the customer, thus reducing the number of names that the customer knows. In addition, these modes allow customers to use classes related to specific applications without changing them.
The following lists some other advantages of the P r o t y p e mode.
1) adding and deleting product P r o t y p e at runtime allows a new product category to be integrated into the system only by registering a prototype instance with the customer. It is more flexible than other creation modes because customers can create and delete prototypes at runtime.
2) A system that changes the value to specify the height of the new object allows you to define a new behavior through the combination of objects-for example, by specifying a value for an object variable-and changing the new class. By instantiating existing classes and registering these instances as prototype of customer objects, You can effectively define objects of new classes. The customer can delegate their responsibilities to the prototype to demonstrate new behaviors.
This design allows you to define a new "class" without programming ". In fact, cloning a prototype is similar to instantiating a class. The P r o t y p e mode can greatly reduce the number of classes required by the system. In our music editor, a G r a p h I c To o l class can create countless music objects.
3) change the structure to specify the new object. Many applications use parts and child parts to create objects. For example, the circuit design editor constructs a circuit by sub-circuit. For convenience, such an application usually allows you to instantiate a complex, user-defined structure. For example, you can reuse a specific sub-circuit over and over again.
The P r o t y p e mode also supports this. We only need to add this sub-circuit as a prototype to the available circuit element selection board. As long as the composite circuit object implements C l o n e as a deep copy, a circuit with different structures can be prototype.
4) reduce the construction of subclass Factory Method (3.3) often generate a C r e a t o r class level parallel to the product class level. The P r o t y p e mode allows you to clone a prototype instead of requesting a factory method to generate a new object. Therefore, you do not need the C r e a t o r class hierarchy. This advantage is mainly applicable to languages such as C ++ that do not use classes as level-1 class objects. Languages such as S m a l t a l k and Objective C have little benefit, because you can always use a class object as the builder. In these languages, class objects have played the same role as prototypes.
5) dynamically configure the runtime environment of the application using the class, allowing you to dynamically load the class into the application. In languages like C ++, the P r o t y p e mode is the key to using this function. An application that wants to create an instance for dynamically loading classes cannot reference the class constructor statically. In
An instance of each class is automatically created during loading and registered with the prototype Manager (see implementation section ). In this way, the application can request the instances of the newly loaded classes from the prototype manager. These classes are not originally connected to the program. E t ++ application framework [w g m 8] has a running system that uses this solution.
The main defect of P r o t y p e is that every subclass of P r o t y p e must implement C l o n e operations, which may be very difficult. For example, it is difficult to add a C l o n e operation when the class already exists. It may be difficult to clone objects that do not support copying or circular references.

This is too long for me to explain. Of course, I also think GoF is very clear here.

I. Is the prototype in "big talk Design Model" correct?

I think "big talk Design Pattern" deviates from the original intention of the prototype pattern here. The following code is taken from "big talk design pattern", and the code before using the prototype Pattern

Resume a = new Resume ("laruence ");
A. setpersonalinfo ("male", "29 ");
A. setworkexperience ("1998-2000", "xx Company ");
// Note: Resume B = a; this is actually a reference, rather than a value. In this way, the Resume is written on B paper and there is no actual content.
Resume B = new Resume ("laruence ");
A. setpersonalinfo ("male", "29 ");
A. setworkexperience ("1998-2000", "xx Company ");
Resume c = new Resume ("laruence ");
A. setpersonalinfo ("male", "29 ");
A. setworkexperience ("1998-2000", "xx Company ");
A. display ();
B. display ();
C. display ();

Code after using the prototype

Resume a = new Resume ("laruence ");
A. setpersonalinfo ("male", "29 ");
A. setworkexperience ("1998-2000", "xx Company ");
// Note: Resume B = a; this is actually a reference, rather than a value. In this way, the Resume is written on B paper and there is no actual content.
Resume B = (Resume) a. clone ();
B. SetWorkExperience ("1998-2000", "yy Company ");
Resume c = (Resume) a. Clone ();
C. SetPersonalInfo ("male", "24 ");
A. display ();
B. display ();
C. display ();

The description in the book is: "Very good, this is actually the code of my handwritten resume era. Three resumes need to be instantiated three times. Do you think the client code is very troublesome? If you need 20 resumes, You need to instantiate them 20 times ."

"And if I write a wrong word, for example, 98 years to 99 years, it will be changed 20 times ."

Is this prototype? Obviously not, it does not meet any of the above applicability scenarios. Let's analyze the problems mentioned below one by one:

Three resumes need to be instantiated three times. Do you think this client code is very troublesome?

Is it troublesome for client code to instantiate three times? I think there is no essential difference between writing three new ones and writing one new two clones.

If you need 20 copies, You need to instantiate them 20 times.

Does clone solve this problem? No, it turns 20 instantiation into one instantiation and 19 clone.

If a wrong word is written, for example, 98 years to 99 years, it will be changed 20 times.

In fact, this is not the problem that the prototype wants to solve. Loop is probably a better idea ......

Never forget the intention of the prototype at any time:Specify a category and create an object.In this example, the types of variables B and c are Resume, which is a specific type. The types of objects referenced by B have no room to specify. So an important sign of determining whether a piece of code is using the prototype isWhether the target variable type referenced after copying is an abstract type.

External 2: Is ICloneable a prototype interface written by. net Framework for us?

Many people think that ICloneable is a Prototype interface written for us in. net. In the Prototype UML, Prototype is ICloneable, right? In my opinion, there is no relationship between ICloneable and prototype. If there is a connection, Prototype can implement ICloneable by the way.

The reason is from the above discussion: What kind of interface should Prototype be? If your code is restructured to the Prototype mode, the Prototype class should exist before the refactoring, but it does not have the clone method. Of course, it must have a name related to its mission, such as Graphic in the GoF example. The Prototype mode only adds a clone method to it, so that we can construct an objectSame type.

All the patterns in the design mode are implicitly contained in a structure in the Code. If the name of a class in your class system is exactly the same as that in the model UML, it must have made a pattern mistake.

 

That's all. Thanks.

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.