设计模式——原型模式

名称 Prototype
结构
意图 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
适用性
  • 当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
  • 为了避免创建一个与产品类层次平行的工厂类层次时;或者
  • 当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

 1// Prototype
 2
 3// Intent: "Specify the kinds of objects to create using a prototypical
 4// instance and create new objects by copying this prototype". 
 5
 6// For further information, read "Design Patterns", p117, Gamma et al.,
 7// Addison-Wesley, ISBN:0-201-63361-2
 8
 9/* Notes:
10 * When we are not in a position to call a constructor for an object 
11 * directly, we could alternatively clone a pre-existing object 
12 * (a prototype) of the same class.
13 * 
14 * This results in specific class knowledge being only required in 
15 * one area (to create the prototype itself), and then later cloned
16 * from code that knows nothing about the cloned prototype, except 
17 * that it exposed a well-known cloning method.  
18 *   
19 */

20 
21namespace Prototype_DesignPattern
22{
23    using System;
24
25    // Objects which are to work as prototypes must be based on classes which 
26    // are derived from the abstract prototype class
27    abstract class AbstractPrototype 
28    {
29        abstract public AbstractPrototype CloneYourself();
30    }

31
32    // This is a sample object
33    class MyPrototype : AbstractPrototype 
34    {
35        override public AbstractPrototype CloneYourself()
36        {
37            return ((AbstractPrototype)MemberwiseClone());
38        }

39        // lots of other functions go here!
40    }

41
42    // This is the client piece of code which instantiate objects
43    // based on a prototype. 
44    class Demo 
45    {
46        private AbstractPrototype internalPrototype;
47
48        public void SetPrototype(AbstractPrototype thePrototype)
49        {
50            internalPrototype = thePrototype;            
51        }

52
53        public void SomeImportantOperation()
54        {
55            // During Some important operation, imagine we need
56            // to instantiate an object - but we do not know which. We use
57            // the predefined prototype object, and ask it to clone itself. 
58
59            AbstractPrototype x;
60            x = internalPrototype.CloneYourself();
61            // now we have two instances of the class which as as a prototype
62        }

63    }

64
65    /// <summary>
66    ///    Summary description for Client.
67    /// </summary>

68    public class Client
69    {
70        public static int Main(string[] args)
71        {                        
72            Demo demo = new Demo();
73            MyPrototype clientPrototype = new MyPrototype();
74            demo.SetPrototype(clientPrototype);
75            demo.SomeImportantOperation();
76
77            return 0;
78        }

79    }

80}

81
原文地址:https://www.cnblogs.com/DarkAngel/p/180830.html