Design Pattern learning 05-prototype Pattern

Source: Internet
Author: User
Tags prototype definition
I. Motivation and definition
Previous Prototype Learning has always assumed that the prototype is intended to easily create identical or similar objects, replace the new method by copying objects, and also studies deep cloning and shortest cloning. Recently I carefully read the gof design model and found that the prototype is not just as simple as copying objects. Copying objects is indeed on the one hand. When we need a large number of similar objects or even the same objects, in addition to new objects, we can also directly copy more objects based on a prototype. However, if we think that the prototype mode is just copying objects, it will be wrong. The creation mode mainly describes how to create objects, including when to create objects, who to create objects, and how to create objects. The intention in the gof book is, Use a prototype instance to specify the type of the object to be created, and create a new object by copying these prototype objects.. In other words, the prototype mode should be understood as specifying the object type to be created first, that is, specifying the object type, and then creating the object through the copy method. Now let's look at the prototype definition to make it clearer: Use the prototype instance to specify the type of the object to be created, and create a new object by copying the prototype. The purpose of the prototype mode is to create an object and create an object through replication. replication is only a method, a method, or a means, rather than a purpose, focusing on Object creation, instead of copying, if you focus on copying objects, it will become a deep cloning study. They are just a method to create objects. Without such cloning, we can also perform cloning on our own.
Ii. Structure and class diagram
The prototype class diagram is as follows:
Prototype: Declare an interface for copying itself. It can be an interface or a class. In fact, copying itself does not have to be in the same state. It will be mentioned later. Concreteprototype: The copied class implements the operation of copying itself. Client: Let a prototype copy itself to create a new object. However, a local clone method is provided in Java to efficiently clone objects. In order to enable all classes to use the general clone method without being affected by a single inheritance, the clone method is put into the object, to use this interface, you only need to implement the cloneable interface. This can only be said that Java provides a very convenient method for us to directly use the prototype (there are many similar methods, such as observer java. util. Observer ). The clone provided by Java by default only clones the basic type and string, that is, the shortest clone. If all objects are cloned, they must be cloned by themselves.
3. Applicable scenarios and effects (advantages and disadvantages)
In my previous understanding, I have always thought that the prototype model has two key points. One is to replace New by copying. Therefore, it is usually difficult and costly to apply a new object, copying is convenient and easy to use. Second, copying an object can save the object state, so you need to retain the object state. There are usually the following application scenarios: 1. It is very simple to copy an object directly when the object creation cost is large. This cost refers to many aspects, such as a long time, a large amount of resource occupation, and a complicated initialization process. 2. When the system needs the object state, for example, if an object has 10 States (or attributes), I need one of the nine states of the object to be the same, and only one State is different, the prototype mode is very convenient (in some cases, re-creation may even fail to obtain the previous status). For example, I want to create a resource access configuration, the resource location, read method, cache size, access permission, access password, and so on are configured. when accessing another resource, only the location is different and the other resources are identical, in this case, you can directly copy an object and modify the resource location status. 3. An object corresponds to multiple modifiers. when an object is used by multiple modifiers, for example, when multiple threads modify an object, you can consider using the prototype mode to create multiple identical objects for callers to avoid resource competition and lock (this depends on your needs, if the purpose is to share resource access, ).
In fact, this is okay, but there is still a gap with gof. gof has four application scenarios: 1. When a system should be independent of its product creation, composition, and representation, prototype mode should be used. This sentence is widely used. In fact, there is a solution under the inverted principle of dependency. Callers cannot depend on specifics but can only rely on abstraction. However, callers do not know the specific product, the factory mode directly requests an object from the factory. The Builder requires an object from the director class, And the singleton mode requires an object from the singleton class, the prototype requires an object from an existing object and requires an object that is exactly the same as yours. 2. When the class to be instantiated is specified at the runtime, for example, through dynamic loading. This refers to the need to dynamically create object types, such as the development of the ground type in the game, grass, snow, cement and so on, the program first creates a prototype of various land, during the runtime, you can determine the type of land to be created based on the parameters. After finding the prototype, copy it. 3. To avoid creating a factory class level parallel to the product class level. This means that sometimes the abstract factory model can be replaced, instead of the factory and factory methods. Instead, the factory method is put into its own clone method and regarded as a factory, in this way, the factory class can be reduced. Although the clone method name is a copy of itself, it is not necessary to copy an object in exactly the same state. Sometimes, as long as the object type is the same, it is not necessary to copy a new object, sometimes it is also possible to return itself out (combined with a singleton ). 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. This is to solve the situation where "only fixed categories of objects, each type of objects may have multiple hours" to create objects, such as pawns in Chinese chess, there are only 7 fixed categories (vehicles, horses, elephants, and artillery), and no other categories are added. Each type has multiple objects (five soldiers and two guns ), we can initialize each piece (7 types of pieces) first, and copy one of them as needed.
// Pawn public class piece {// type private int type; // name private string name; // status private string state; // color private string color; // other attributes ......}
Of course, if the type and quantity are fixed, you can consider using generics. Let's talk about the effect after use, that is, the advantages: 1. Similar to the factory and builder modes, it encapsulates the underlying implementation, relies on abstract products, and hides specific products, reduce Code complexity (fewer classes) and so on. I will not detail it here. 2. add or delete products at runtime. This means that you do not need to create a new product class when using different products. You can use an attribute status to control the object type, such as the pawns in the preceding example, there is no need to create a class for each piece. You only need a type to control which piece is used. When the caller uses it, he can dynamically create and reduce the product class. It also reduces the number of classes and simplifies the code. However, this depends on the actual situation. Only when the object types are very similar can this problem be solved. 3. Change the value to specify a new object. Similar to the above, you only need to modify the product property value to create a new product, which is very convenient. 4. Change the structure to specify a new object. This is to directly create a completely new product by means of a deep clone and use it directly, which is very convenient. For example, four auto tires are required. It is costly to create one. However, it is easy to copy four tires after one is created. 5. Reduce the subclass construction. As mentioned above, the clone method reduces the factory class compared to the factory method. The clone method is directly put into the product, adding a subclass without adding factories, simplified the code. 6. with dynamic configuration applications of classes, we can put some configurations into an object and provide a copy of this configuration object for external use. After dynamic modification of the configuration object, the use of the old object is not affected, but the new configuration can be used for the new use of the configuration. Disadvantages: 1. disadvantages of the prototype mode are also obvious. All sub-classes must implement the clone method. The newly designed program is fine, and it is troublesome to transform the original program, it is too difficult to add a clone method to all classes one by one. 2. Unable to clone the object. The method of cloning the object looks good, but there is a problem. What should I do if some objects cannot be cloned, and some objects are too complicated to be cloned, for example, if a property in Java uses the final keyword and cannot be assigned twice, deep cloning cannot be implemented. In another case, internal attributes are referenced by each other and referenced cyclically. In this case, cloning is very difficult. 3. Deep cloning requires complex code.
Iv. Mode Scaling
There is a disadvantage for the caller to directly copy the prototype. The caller's role is unclear. The prototype he or she needs to use may not be distinguished between the prototype and the copied product (most of the time there is no need to distinguish between the prototype ), therefore, there is a way to introduce the prototype manager to manage the prototype and maintain the list of existing prototype. The caller sends a request to the prototype manager to obtain the prototype, so that the caller does not need to know the prototype, the prototype and the copied product can also be differentiated. Compared with other creation modes, this mode has no factory, no Singleton, no director class. The prototype only requires one product prototype to replicate other products, so it is very flexible, the caller can dynamically add and delete products at runtime without having to write a bunch of classes such as factory, Singleton, and builder.

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.