原型模式:通过给出一个原型对象来指明所要创建的对象类型,然后用复制这个原型对象的办法创建出更多的同类型对象。
原型模式类图:
类图说明:
客户(Client)角色:客户类提出创建对象的请求。
抽象原型(Prototype)角色:这是一个抽象角色,通常由一个 C#接口或抽象类实现。此角色给出所有的具体原型类所需的接口。在 C#中,
抽象原型角色通常实现了 ICloneable 接口。
具体原型(Concrete Prototype)角色:被复制的对象。此角色需要实现抽象原型角色所要求的接口。
示例代码:
class Program { static void Main(string[] args) { ConcreteProtoType1 p1 = new ConcreteProtoType1("I"); ConcreteProtoType1 c1 = (ConcreteProtoType1)p1.Clone(); Console.WriteLine("Cloned:{0}", c1.Id); ConcreteProtoType2 p2 = new ConcreteProtoType2("II"); ConcreteProtoType2 c2 = (ConcreteProtoType2)p2.Clone(); Console.WriteLine("Cloned:{0}", c2.Id); Console.ReadKey(); } } abstract class ProtoType { private string id; public ProtoType(string id) { this.id = id; } public string Id { get { return id; } } abstract public ProtoType Clone(); } class ConcreteProtoType1 : ProtoType { public ConcreteProtoType1(string id) : base(id) { } public override ProtoType Clone() { return (ProtoType)this.MemberwiseClone(); } } class ConcreteProtoType2 : ProtoType { public ConcreteProtoType2(string id) : base(id) { } public override ProtoType Clone() { return (ProtoType)this.MemberwiseClone(); } }