代码改变世界

原型模式

2011-03-06 08:29  杨延成  阅读(263)  评论(0编辑  收藏  举报
1namespace Prototype
2{
3 class Program
4{
5 static void Main(string[] args)
6{
7
8 MyPrototype my = new MyPrototype();
9 my.PropertyTest = \"test\";
10
11 my.ShowProperty();
12
13 //未使用管理器
14 //MyPrototype newMy = my.Clone() as MyPrototype;
15 //newMy.ShowProperty();
16
17
18
19///使用管理器
20 PrototypeManager pm = new PrototypeManager();
21 pm = my;
22 pm = new MyPrototype(\"second\");
23 MyPrototype newMy = pm.Clone() as MyPrototype;
24 newMy.ShowProperty();
25
26
27 }
28 }
29
30 public interface IPrototype
31{
32 IPrototype Clone();
33 }
34
35
36#region prototype
37
38///
39 /// 原型
40 ///
41
public class MyPrototype : IPrototype
42{
43 private string propertyTest;
44
45 public string PropertyTest
46{
47 get { return propertyTest; }
48 set { propertyTest = value; }
49 }
50
51 public MyPrototype()
52{
53 this.propertyTest = \"Init String\";
54 }
55 public MyPrototype(string propertyTest)
56{
57 this.propertyTest = propertyTest;
58 }
59
60 public void ShowProperty()
61{
62 Console.WriteLine(propertyTest);
63 }
64
65#region IPrototype Members
66
67 public IPrototype Clone()
68{
69
70///深拷贝
71 ///
72 return new MyPrototype(propertyTest);
73
74///浅拷贝
75 ///
76 // return this.MemberwiseClone() as IPrototype;
77
78 }
79
80 #endregion
81 }
82 #endregion
83
84
85///
86 /// 管理器
87 ///
88
public class PrototypeManager
89{
90 private Dictionary<string, IPrototype> prototypeManager = new Dictionary<string, IPrototype>();
91 public IPrototype this
92{
93{
94 prototypeManager.Add(propertyTest, value);
95 }
96 get
97{
98 return prototypeManager;
99 }
100 }
101 }
102
103}

在以下几种情况中应当采用原型模式来创建对象:
1、对象的构造函数非常复杂,在生成新对象的时候非常耗时间、耗资源的情况,使用原型模式可以简捷地创建新对象。
2、程序运行过程中,由于一些数据随进都在变化,事后很难使用构造函数再构造出一个和原来一样的对象。
3、不知道当前对象的状态,即目前不知道当前对象成员变量的值都变成了什么内容,故无法再用构造函数来构造和当前对象一样的对象了。