Design Pattern 6: Prototype pattern (prototype pattern)

Source: Internet
Author: User

From: http://www.cnblogs.com/zhenyulu/articles/39257.html

Reference: http://www.dofactory.com/Patterns/PatternPrototype.aspx

I. prototype mode

Definition: Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.

The purpose of the prototype mode is to specify the type of the object to be created by giving a prototype object, and then create more objects of the same type by copying the prototype object.

Talking about Sun dasheng's means

Sun Wukong is fighting with Huang fengblame. "A means to make an out-Of-The-body: Hold off your hair, chew it with your mouth, and look at it with a spray. The cry is changed ', as many as people dressed in the same way, each person held an iron rod and placed the blame in the air. "In other words, Sun Wukong can copy a lot of" out of the body "based on his own image.

Old sun's external means is called prototype in the field of object-oriented design.

C # support for prototype

In C #, we can easily implement the prototype through the clone () method. To support cloning any class, you must implement the icloneable interface in C. There is a clone method in the icloneable interface, which can be rewritten in the class to implement a custom clone method. There are two clone implementation methods: shallow copy and deep copy ).

(The following is an excerpt from. NET Framework programming (revised version), translated by Li Jianzhong). When a field value of an object is copied, the object referenced by the field is not copied. For example, if an object has a field pointing to a string and we make a shortest copy of the object, the two objects will reference the same string. Deep copy is also a method for copying objects referenced by fields in the object instance. Therefore, if an object has a field pointing to a string, if we make a deep copy of the object, we will create a new object and a new string-the new object will reference the new string. Note that after deep copy, the original object and the newly created object will not share anything; changing an object will not affect the other object.

Ii. Structure of prototype mode:

 

Client role: the customer class initiates a request to create an object.
Prototype role: This is an abstract role, usually implemented by a C # interface or abstract class. This role provides all the interfaces required for the specific prototype class. In C #, the abstract prototype role usually implements the icloneable interface.
Concrete prototype: the object to be copied. This role must implement the interface required by the abstract prototype role.

3. program example:

The following program provides a schematic implementation:

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; </P> <p> namespace protypepattern <br/>{< br/> abstract class prototype <br/>{< br/> // fields <br/> private string ID; </P> <p> // constructors <br/> Public prototype (string ID) <br/> {<br/> This. id = ID; <br/>}</P> <p> Public String id <br/>{< br/> get {return ID ;} <br/>}</P> <p> // methods <br/> Abstract Public prototype clone (); <br/>}</P> <p> // "concreteprototype1" <br/> class concreteprototype1: prototype <br/> {<br/> // constructors <br/> Public concreteprototype1 (string ID): Base (ID) {}</P> <p> // methods <br/> override public prototype clone () <br/>{< br/> // shallow copy <br/> return (prototype) This. memberwiseclone (); <br/>}</P> <p>/"concreteprototype2" <br/> class concreteprototype2: prototype <br/> {<br/> // constructors <br/> Public concreteprototype2 (string ID): Base (ID) {}</P> <p> // methods <br/> override public prototype clone () <br/>{< br/> // shallow copy <br/> return (prototype) This. memberwiseclone (); <br/>}</P> <p>/**/<br/> /// <summary> <br/> // client Test <br/> // </Summary> <br/> class client <br/> {<br/> Public static void main (string [] ARGs) <br/>{< br/> // create two instances and clone each <br/> concreteprototype1 p1 = new concreteprototype1 ("I "); <br/> concreteprototype1 C1 = (concreteprototype1) p1.clone (); <br/> console. writeline ("cloned: {0}", c1.id); </P> <p> concreteprototype2 P2 = new concreteprototype2 ("II "); <br/> concreteprototype2 C2 = (concreteprototype2) p2.clone (); <br/> console. writeline ("cloned: {0}", c2.id); <br/>}< br/>

This example implements a shortest copy. The memberwiseclone () method is a protected method of the object class, which implements the shortest copy of the object. If you want to implement a deep copy, you should implement the icloneable interface and write the clone interface method of icloneable.

4. Prototype manager prototype

The second form of the prototype mode is the prototype mode with the prototype Manager. The UML diagram is as follows:

 

Client role: the client class sends a request to the prototype manager to create an object.
Prototype role: This is an abstract role, usually implemented by a C # interface or abstract class. This role provides all the interfaces required for the specific prototype class. In C #, the abstract prototype role usually implements the icloneable interface.
Concrete prototype: the object to be copied. This role must implement the interfaces required by the abstract prototype role.
Prototype manager role: Creates objects of a specific prototype class and records each created object.

The following example demonstrates how to store a user-defined color prototype in the prototype Manager. The customer clones a color object through the prototype manager.

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; </P> <p> namespace protypepattern <br/>{< br/> abstract class colorprototype <br/>{< br/> // methods <br/> public abstract colorprototype clone (); <br/>}</P> <p> // "concreteprototype" <br/> class color: colorprototype <br/>{< br/> // fields <br/> private int red, green, blue; </P> <p> // constructors <br/> Public color (INT red, int green, int blue) <br/>{< br/> This. red = red; <br/> This. green = green; <br/> This. blue = blue; <br/>}</P> <p> // methods <br/> Public override colorprototype clone () <br/> {<br/> // creates a 'shallow copy' <br/> return (colorprototype) This. memberwiseclone (); <br/>}</P> <p> Public void display () <br/>{< br/> console. writeline ("RGB values are: {0}, {1}, {2}", <br/> red, green, blue ); <br/>}</P> <p> // prototype manager <br/> class colormanager <br/>{< br/> // fields <br/> hashtable colors = new hashtable (); </P> <p> // indexers <br/> Public colorprototype this [string name] <br/> {<br/> get {return (colorprototype) colors [name] ;}< br/> set {colors. add (name, value );} <br/>}</P> <p>/**/<br/> /// <summary> <br/> // prototypeapp Test <br/> // </Summary> <br/> class prototypeapp <br/> {<br/> Public static void main (string [] ARGs) <br/>{< br/> colormanager = new colormanager (); </P> <p> // initialize with standard colors <br/> colormanager ["red"] = new color (255, 0, 0 ); <br/> colormanager ["green"] = new color (0,255, 0); <br/> colormanager ["blue"] = new color (0, 0,255 ); </P> <p> // user adds personalized colors <br/> colormanager ["Angry"] = new color (255, 54, 0 ); <br/> colormanager ["peace"] = new color (128,211,128); <br/> colormanager ["Flame"] = new color (211, 34, 20 ); </P> <p> // user uses selected colors <br/> string colorname = "red"; <br/> color C1 = (color) colormanager [colorname]. clone (); <br/> c1.display (); </P> <p> colorname = "peace"; <br/> color C2 = (color) colormanager [colorname]. clone (); <br/> c2.display (); </P> <p> colorname = "Flame"; <br/> color C3 = (color) colormanager [colorname]. clone (); <br/> c3.display (); <br/>}< br/>

V. Shallow copy and deep copy

The following two examples are provided: shallow copy and deep copy. The icloneable interface is used in this example. Arrays in C # are referenced variables. We use Arrays for Demonstration:

Shallow copy:

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; </P> <p> namespace protypepattern <br/> {<br/> class shallowcopy: icloneable <br/>{< br/> Public int [] V = {1, 2, 3 }; </P> <p> Public object clone () <br/>{< br/> return this. memberwiseclone (); <br/>}</P> <p> Public void display () <br/>{< br/> foreach (int I in V) <br/> console. write (I + ","); <br/> console. writeline (); <br/>}</P> <p> class client <br/>{< br/> Public static void main () <br/>{< br/> shallowcopy SC1 = new shallowcopy (); <br/> shallowcopy SC2 = (shallowcopy) sc1.clone (); <br/> sc1.v [0] = 9; </P> <p> sc1.display (); <br/> sc2.display (); <br/>}< br/>
Shallowcopy object implements a shallowcopy object. Therefore, when SC1 is cloned, its field V is not cloned. As a result, the fields V of SC1 and SC2 point to the same v. Therefore, after the V [0] of SC1 is modified, the V [0] of SC2 also changes.

Deep copy:

Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; </P> <p> namespace protypepattern <br/> {<br/> class deepcopy: icloneable <br/>{< br/> Public int [] V = {1, 2, 3 }; </P> <p> // default constructor <br/> Public deepcopy () <br/>{< br/>}</P> <p> // private constructor called by the clone method <br/> private deepcopy (INT [] V) <br/>{< br/> This. V = (INT []) v. clone (); <br/>}</P> <p> Public object clone () <br/>{< br/> // construct a new deepcopy object, the construction parameter is <br/> // v used in the original object <br/> return New deepcopy (this. v); <br/>}</P> <p> Public void display () <br/>{< br/> foreach (int I in V) <br/> console. write (I + ","); <br/> console. writeline (); <br/>}</P> <p> class client <br/>{< br/> Public static void main () <br/>{ <br/> deepcopy DC1 = new deepcopy (); <br/> deepcopy DC2 = (deepcopy) dc1.clone (); <br/> dc1.v [0] = 9; </P> <p> dc1.display (); <br/> dc2.display (); <br/>}< br/>
During this cloning, not only the object itself is cloned, but the array fields in the object are cloned together. Therefore, the printed DC1 is different from DC2.

Vi. Advantages and Disadvantages of prototype mode

Advantages of the prototype mode include:

1. The prototype mode allows you to dynamically add or remove product classes. Because the method used to create a product-class instance is internal to the production and batch class, adding a new product does not affect the entire structure.

2. The prototype mode provides a simplified creation structure. The factory method mode usually requires a hierarchical structure that is the same as the product class level structure, but the prototype mode does not.

3. The portotype mode can dynamically load new functions for an application. Because prototype is highly independent, it is easy to dynamically load new features without affecting the old system.

4. Product classes do not need to have any pre-determined level structure, because the prototype mode applies to any level structure.


Disadvantages of prototype mode:

The main disadvantage of the prototype mode is that each class must have a clone method. In addition, this cloning method requires a comprehensive consideration of the functions of the class, which is not very difficult for the brand-new class, but it is not always easy to transform the existing class.

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.