C # design Pattern five-prototype mode (Prototype pattern) "created"

Source: Internet
Author: User

Original: C # design pattern of the five prototype pattern (Prototype pattern) "created"

First, Introduction

Before you start today's article, please explain it. Many people say that prototyping patterns save machine memory, which they say is a copy of objects that are actually copied from the prototype and do not use memory. I think this is wrong, because every object that is copied is actually present, and each object has its own independent memory address, which is recycled by GC. In the case of a shallow copy, some fields may be common, and deep copies will not, so the prototype design pattern will increase memory usage, not necessarily. It depends on the design, if the copy of the object cache, each use of the cached copy object, it is another matter, and the pattern itself solves the problem is not memory utilization.
Now talk about the prototype model to solve the problem, in the software system, when the process of creating an instance of a class is expensive or complex, and we need to create multiple instances of such classes, if we use the new operator to create such a class instance, This increases the complexity of creating classes and the complex coupling of the creation process to customer code. If you use Factory mode to create such an instance object, as the product class continues to increase, resulting in a growing number of subclasses, resulting in the increase in the corresponding factory class, the maintenance of the code dimension increased, because there are two dimensions of the product and the factory, but increase the complexity of the system, So it is not appropriate to use Factory mode to encapsulate the class creation process here. Because each class instance is the same, this same refers to the same type, but each instance of the state parameter will be different, if the status of the same value is meaningless, there is one such object can be. When we need more than one instance of the same class, we can create it by copying a copy of the original object, which is how the prototype pattern is implemented.

second, the prototype model of the detailed introduction

2.1. Motive (motivate)

In the software system, it is often confronted with the creation of "some complex objects", and because of the change of demand, these objects often face drastic changes, but they have more stable and consistent interfaces. How to deal with this change? How do you isolate "these volatile objects" from "Client programs (Programs that use these objects)" so that "client programs that rely on these volatile objects" do not change as demand changes?

2.2. Intention (Intent)

Use the prototype instance to specify the kind of object to create, and then copy the prototypes to create new objects. --"Design pattern" Gof

2.3. structure diagram (Structure)



2.4, the composition of the model

As you can see, the structure diagram in the prototype pattern has the following roles:

(1), prototype class (Prototype): A prototype class that declares a clone's own interface;

(2), Concrete prototype class (Concreteprototype): Implements the operation of a clone itself.

In prototype mode, prototype typically provides an interface that contains the Clone method, and the specific prototype Concreteprototype uses the Clone method to complete the creation of the object.

2.5 Specific implementations of prototype patterns

"Big talk West tour of the Holy of the Wedding" this film, have not seen a lot of people, there is such a scene. Ox Demon King use Invincible bull lice War Supreme Treasure, the supreme treasure of the strategy is to take the next pinch of monkey hair from behind the brain, blowing the mouth of fairy gas, countless monkeys monkey Sun appeared, to fight the invincible cattle lice Ox Demon King. The Supreme Treasure Monkey Monkey Sun is the best embodiment of the prototype model. Supreme Treasure to create a copy of their own, do not have to be re-bred 500 years, and then born, and then The Apprentice, and finally to the old bull war, estimated that the flowers are cold. He has 3 life-saving monkey hair, gently blowing, want to how many of their own, convenient, fast.

1 /// <summary>2 ///prototype design pattern, each concrete prototype is a class of objects of the original object, through each prototype object cloned objects can also be set, on the basis of the prototype to enrich the cloned objects, so design the interface of the abstract prototype3 /// </summary>4 namespaceprototype mode of design pattern5 {6     /// <summary>7     ///Customer Class8     /// </summary>9     classCustomerTen     { One         Static voidMain (string[] args) A         { -Prototype Xingzhesun =NewXingzhesunprototype (). Clone (); -Prototype xingZheSun2 =NewXingzhesunprototype (). Clone (); thePrototype XINGZHESUN3 =NewXingzhesunprototype (). Clone (); -  -Prototype Sunxingzhe =NewSunxingzheprototype (). Clone (); -Prototype sunXingZhe2 =NewSunxingzheprototype (). Clone (); +Prototype SunXingZhe3 =NewSunxingzheprototype (). Clone (); -Prototype sunXingZhe4 =NewSunxingzheprototype (). Clone (); +Prototype sunXingZhe5 =NewSunxingzheprototype (). Clone (); A  at             //No. 1th, Samson hit the Monsters . - sunxingzhe.fight (); -             //number 2nd, Sun Walker, to alms. - Sunxingzhe2.begalms (); -  -             //Combat and alms can also be classified, such as alms, can be divided into: fruit class alms, meals alms; Fighting can be classified as: Heavenly Pet Nether into a demon battle, natural cultivation into the battle of demons, we can think of it yourself, prototype mode is still very useful in  - Console.read (); to         } +     } -  the     /// <summary> *     ///An abstract prototype that defines the characteristics and actions of the prototype itself, which is the ultimate treasure $     /// </summary>Panax Notoginseng      Public Abstract classPrototype -     { the         //fighting-Protecting the master +          Public Abstract voidfight (); A         //alms--Don't be hungry, master. the          Public Abstract voidBegalms (); +  -         //Blow the breath--change a self out $          Public AbstractPrototype Clone (); $     } -  -     /// <summary> the     ///specific prototypes, such as: Walker, he is only responsible for the Iftar food and the heavenly Pet Nether Monsters of the battle -     /// </summary>Wuyi      Public Sealed classXingzhesunprototype:prototype the     { -         //fighting--protecting the master--the battle with natural cultivation into a demon Wu          Public Override voidfight () -         { AboutConsole.WriteLine ("clouds, various martial arts"); $         } -         //alms--Don't be hungry master--meals -          Public Override voidBegalms () -         { AConsole.WriteLine ("Everything 's going to be here."); +         } the  -         //Blow the breath--change a self out $          Public OverridePrototype Clone () the         { the             return(Xingzhesunprototype) This. MemberwiseClone (); the         } the     } -  in     /// <summary> the     ///concrete Prototypes, for example: Sun Xing, he is only responsible for the fight with nature and Huazai fruit the     /// </summary> About      Public Sealed classSunxingzheprototype:prototype the     { the         //Battle-Protect master-battle with heavenly Pets the          Public Override voidfight () +         { -Console.WriteLine ("clouds, various martial arts"); the         }Bayi         //alms-Don't be hungry master---fruit the          Public Override voidBegalms () the         { -Console.WriteLine ("Everything 's going to be here."); -         } the  the         //Blow the breath--change a self out the          Public OverridePrototype Clone () the         { -             return(Sunxingzheprototype) This. MemberwiseClone (); the         } the     } the}


There is detailed comment code in the code above, and there is not much to explain here.

three, the main points of the prototype model implementation:

The prototype pattern is also used to isolate the coupling between the consumer of a class object and the specific type (variable Class), which also requires these "variable classes" to have "stable interfaces".

The prototype mode is a "prototype clone" method for "how to create a variable class entity object" (in addition to the singleton mode, which is used to solve the problem of creating a variable class entity object), which gives us the flexibility to dynamically create "have certain stable interfaces" New Object-The only job required is to register the object of a new class (that is, the prototype) and then clone it wherever it is needed.

The Clone method in prototype mode can take advantage of the MemberwiseClone () method or serialization of the object class in. NET to implement a deep copy.

3.1 ", the advantages of prototype mode:

(1), prototype mode hides the complexity of creating a new instance to the customer

(2), prototype mode allows dynamic addition or fewer product classes.

(3), the prototype mode simplifies the creation of the instance structure, the factory method pattern needs to have the same hierarchy structure as the product class grade structure, and the prototype mode does not need this.

(4), product class does not need to determine the grade structure of the product beforehand, because the prototype mode applies to any hierarchy structure

3.2 ", the disadvantage of prototype mode:

(1), each class must be equipped with a cloning method

(2), equipped with a cloning method requires a comprehensive consideration of the function of the class, which is not difficult for the new class, but for the existing classes may not be very easy, especially when a class reference does not support serialization of indirect objects, or reference containing a loop structure.

3.3 ", prototype mode uses the scene:

(1), resource optimization scenario

Class initialization requires a lot of resources to digest, including data, hardware resources, and so on.

(2), performance and safety requirements of the scene

A prototype pattern can be used to produce an object through new that requires very tedious data preparation or access rights.

(3), a scene with multiple modifiers for an object

When an object needs to be provided to other object access, and each caller may need to modify its value, consider copying multiple objects using prototype mode for the caller to use.

In real-world projects, prototype patterns rarely appear alone, typically in conjunction with the factory method pattern, creating an object by using clone, which is then provided by the factory method to the caller.

realization of the model of. NET

In. NET, Microsoft has provided us with the prototype model of the interface implementation, which is icloneable, in fact, this interface is an abstract prototype, providing a cloning method, equivalent to the above code in the prototype abstract class, wherein the Clone () method to implement the prototype mode, If we want our custom classes to have cloning capabilities, first define the class implementation of the Clone method of the ICloneable interface. In fact. NET implements the ICloneable interface in a number of classes, as shown in (the figure is only part of the interception, can be viewed with the Ilspy Anti-compilation tool):

namespace system{    [ComVisible (true)]    publicinterface  icloneable    {        object  Clone ();    }}

In the net FCL implementation of the ICloneable interface class, you can go to see each class their own implementation, not posted here.



V. Summary

So far, all of the created design patterns have been written. Learning design patterns should be a gradual process, when we write code not to use what design patterns, but by refactoring to use design patterns. The design pattern of creation is finished, let's summarize. Singleton single-piece mode solves the problem of the number of entity objects. In addition to Singleton, the other creation pattern solves the coupling relationship that new brings. Factory Method,abstract Factory,builder requires an additional factory class to instantiate "volatile objects", while prototype clones "variable objects" through prototypes (a special factory class). (In fact, the prototype is a special factory class, it just coupling the factory and the entity objects together). If a "variable class" is encountered, the initial design usually starts with the Factory method, and when more complex changes are encountered, it is considered to be refactored into the other three plant modes (Abstract factory,builder,prototype).
In general, if you can use factory Method, you can always use prototype. However, the use of prototype is generally in the class is relatively easy to clone the condition above, if each class implementation is relatively simple, can only be implemented MemberwiseClone, no reference type of deep copy, then it is more appropriate.

C # design Pattern five-prototype mode (Prototype pattern) "created"

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.