设计模式之 原型模式


原型模式的作用 就是 拷贝要创建类的对象,
1
/// <summary> 2 /// 用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象. 3 /// 4 /// 5 ///Singleton模式解决的是实体对象个数的问题。除了Singleton之外, 6 ///其他创建型模式解决的是都是new 所带来的耦合关系。 7 //Factory Method ,Abstract Factory,Builder都需要一个额外的工 8 //厂类来负责实例化“易变对象”,而Prototype则是通过原型 9 //(一个特殊的工厂类)来克隆“易变对象”。 10 //如果遇到“易变类”,起初的设计通常从Factory Mehtod开始, 11 //当遇到更多的复杂变化时,再考虑重重构为其他三种工厂模式 12 //(Abstract Factory,Builder,Prototype). 13 14 /// </summary> 15 class Program 16 { 17 static void Main(string[] args) 18 { 19 20 CloneProtype1 p1 = new CloneProtype1("1"); 21 CloneProtype1 c1 = (CloneProtype1)p1.Clone(); 22 Console.WriteLine(c1.ID); 23 Console.Read(); 24 } 25 } 26 abstract class ProtoType 27 { 28 private string id; 29 public ProtoType(string id) 30 { 31 this.id = id; 32 } 33 public string ID 34 { 35 get { return id; } 36 } 37 public abstract ProtoType Clone(); 38 39 } 40 class CloneProtype1 : ProtoType 41 { 42 public CloneProtype1(string id) 43 : base(id) 44 { 45 46 } 47 public override ProtoType Clone() 48 { 49 return (ProtoType)MemberwiseClone(); 50 } 51 } 52 53 class CloneProType2 : ProtoType 54 { 55 public CloneProType2(string id) 56 : base(id) 57 { 58 } 59 public override ProtoType Clone() 60 { 61 return (ProtoType)MemberwiseClone(); 62 } 63 }

 

posted @ 2014-11-27 20:58  落日云烟  阅读(96)  评论(0编辑  收藏  举报