Design mode: Prototype mode

Source: Internet
Author: User

Definition of prototype pattern:

Prototype mode: Use the prototype instance to specify the type of object to be created, and create a new object by copying the prototype.

Structure of the prototype pattern:

The prototype pattern mainly consists of 3 roles:

    

(1) Prototype (Abstract prototype Class): The interface that declares the cloning method, is the common parent class of all the concrete prototype classes, but the abstract class can also be an interface, or even a concrete implementation class.

(2) Concreteprototype (Concrete prototype Class): It implements the cloned method declared in the abstract prototype class and returns its own clone object in the Clone method.

(3) Client: In the Customer class, let a prototype object clone itself to create a new object.

Deep cloning and shallow cloning:

Shallow cloning: When a prototype object is copied, only the member variables of its own and the value types contained therein are copied, and the member variables of the reference type are not copied.

    

Deep clones: All member variables contained in the object are copied, in addition to the object itself being copied.

    

The implementation of the prototype pattern:

In the use of an OA system, some staff found that their weekly work is similar, so in the completion of the weekly work is a lot of content is repeated, in order to improve the efficiency of the creation of weekly work, there is an urgent need for a mechanism to quickly create the same or similar weekly, including the creation of weekly report attachments. This paper tries to improve the module of working weekly in the OA system using prototype mode.

  

The code is as follows:

Weeklylog: Weekly Series

[Serializable] Public classWeeklylog { PublicAttachment Attachment {Get;Set; }  Public stringName {Get;Set; }  Public stringDate {Get;Set; }  Public stringContent {Get;Set; } /// <summary>        ///use MemberwiseClone () for shallow cloning/// </summary>        /// <returns></returns>        //Public Weeklylog Clone ()//{        //return (Weeklylog) this.        MemberwiseClone (); //}        //using serialization to implement deep clones         PublicWeeklylog Clone () {Weeklylog clone=NULL; FileStream FS=NewFileStream ("Temp.dat", FileMode.Create); BinaryFormatter Formatter=NewBinaryFormatter (); Try{Formatter. Serialize (FS, This); }            Catch(SerializationException e) {Console.WriteLine ("Failed to Serialize. Reason:"+e.message); Throw; }            finally{fs.            Close (); } FileStream FS1=NewFileStream ("Temp.dat", FileMode.Open); BinaryFormatter Formatter1=NewBinaryFormatter (); Try{Clone= (Weeklylog) formatter. Deserialize (FS1);//deserialization            }            Catch(SerializationException e) {Console.WriteLine ("Failed to deserialize. Reasion:"+e.message); Throw; }            finally{FS1.            Close (); }            returnclone; }    }

Attachmeht: Accessory Class

    [Serializable]    publicclass  Attachment    {        public string Get Set ; }          Public void dowmload ()        {            Console.WriteLine (" download attachment, file name {0}", name);}    }

Client code:

        Static voidMain (string[] args)            {Weeklylog log, log_new; Log=NewWeeklylog (); Attachment attchment=NewAttachment (); Log. Attachment=attchment; Log_new=log.            Clone (); System.Console.WriteLine ("is the weekly report the same? {0}", Log==log_new?"is a":"No"); System.Console.WriteLine ("is the attachment the same? {0}", log. Attachment = = Log_new. Attachment?"is a":"No");        System.Console.ReadKey (); }

Prototype Manager:

  Storing multiple prototype objects in a collection for client use is a factory dedicated to cloning objects, where a collection is defined to store the prototype object, and if a clone of a prototype object is needed, it can be obtained by copying the corresponding prototype object in the collection.

  

The code is as follows:

     Public classPrototypemanager {Hashtable HT=NewHashtable ();  PublicPrototypemanager () {ht. ADD ("A",NewConcreteprototypea ()); Ht. ADD ("B",NewConcreteprototypeb ()); }         Public voidADD (stringkey, Prototype Prototype) {ht.        ADD (key, prototype); }         PublicPrototype Get (stringkey) {Prototype clone=NULL; Clone=((Prototype) Ht[key]).            Clone (); returnclone; }    }     Public Abstract classPrototype { Public AbstractPrototype Clone (); }     Public classConcreteprototypea:prototype { Public OverridePrototype Clone () {return(CONCRETEPROTOTYPEA) This.        MemberwiseClone (); }    }     Public classConcreteprototypeb:prototype { Public OverridePrototype Clone () {return(CONCRETEPROTOTYPEB) This.        MemberwiseClone (); }    }

In the actual development, Prototypemanager can be designed as a singleton mode, ensuring that there is only one Prototypemanager object in the system, which can save the system resources and better control the object of the prototype manager ....

Advantages and disadvantages of prototype mode:

Advantages: (1): When creating an instance of an object is more complex, the use of prototype mode can simplify the creation of the object, by copying an existing instance can improve the efficiency of the creation of the instance.

(2): extensibility, because the prototype model provides an abstract prototype class, in the client for the abstract prototype class programming, and the specific prototype class written to the configuration file, add or subtract or reduce the product has no effect on the original system.

(3): Prototype mode provides a simplified creation structure, and the factory method pattern often requires a factory hierarchy structure that is the same as the product class hierarchy, and the prototype mode does not need this, and the copy of the product in circular mode is implemented by encapsulating the cloning method in the class, without requiring a specialized factory class to create the product.

(4): You can use deep cloning to save the state of an object, use prototype mode to copy an object and save its state so that it can be used when needed (such as reverting to a state of history), to assist in the implementation of the undo operation.

Cons: (1): You need to configure a clone method for each class, and the Clone method is inside the class, when the existing class is reformed, the code needs to be modified, violating the open and closed principle.

(2): In the implementation of deep cloning needs to write more complex code, and when there are multiple check-in references between objects, in order to achieve deep cloning, each layer of objects corresponding to the class must support deep cloning, the implementation will be more troublesome.

The applicable environment for prototype mode:

1: Creating a new object is expensive (for example, it takes a long time to initialize, consumes more CPU, or makes up too many network resources), the new object can be obtained by copying existing objects, and if similar objects, it can modify its member variables slightly.

2: The system wants to save the state of the object, while the object's state is small.

3: You need to avoid using hierarchical factory classes to create hierarchical objects, and instance objects of a class have only one or few combined states, and it is easier to copy a prototype object to get a new instance than to use a constructor to create a new instance.

Design mode: Prototype mode

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.