原型模式
意图:
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
适用性:
当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者
为了避免创建一个与产品类层次平行的工厂类层次时;或者
当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。
下面针对结构图写个简单的实现
首先定义一个抽象原型类Prototype
1 public abstract class Prototype 2 { 3 private string _id; 4 public Prototype(string id) { this._id = id; } 5 public string Id { get { return _id; } } 6 public abstract Prototype Clone(); 7 }
然后在定义两个具体的实现类
1 public class ConcretePrototype1 : Prototype 2 { 3 public ConcretePrototype1(string id) : base(id) { } 4 public override Prototype Clone() 5 { 6 return (Prototype)this.MemberwiseClone(); 7 } 8 } 9 public class ConcretePrototype2 : Prototype 10 { 11 public ConcretePrototype2(string id) 12 : base(id) 13 { 14 } 15 public override Prototype Clone() 16 { 17 return (Prototype)this.MemberwiseClone(); 18 } 19 }
客户端调用如下
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Prototype prototype1 = new ConcretePrototype1("1"); 6 Prototype p1 = prototype1.Clone(); 7 Prototype prototype2 = new ConcretePrototype2("2"); 8 Prototype p2 = prototype2.Clone(); 9 Console.WriteLine("p1:{0},p2:{1}", p1.Id, p2.Id); 10 Console.Read(); 11 } 12 }
输出结果:p1:1,p2:2
这就是原型模式的简单实现过程,在过程中通过拷贝来创建一个实例。