一、介绍
用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。Prototype原型模式是一种创建型设计模式,Prototype模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节,工作原理是:通过将一个原型对象传给那个要发动创建的对象,这个要发动创建的对象通过请求原型对象拷贝它们自己来实施创建。
二、UML图
三、示例
View Code
public class Dog { /// <summary> /// 名称 /// </summary> public string Name { get; set; } /// <summary> /// 行为 /// </summary> public string Action { get; set; } } /// <summary> /// 浅拷贝 /// </summary> public class ShallowClone : ICloneable { #region IClone 成员 public ShallowClone(Dog model, string Tag) { this.DogModel = model; this.Tag = Tag; } public object Clone() { return this.MemberwiseClone(); } public string Tag { get; set; } /// <summary> /// 实体属性 /// </summary> public Dog DogModel { get; set; } #endregion } /// <summary> /// 深拷贝 /// </summary> public class DeepClone : ICloneable { #region IClone 成员 public DeepClone(Dog model, string tag) { this.DogModel = model; this.Tag = tag; } public object Clone() { return new DeepClone(new Dog { Name = DogModel.Name, Action = DogModel.Action },this.Tag); } public string Tag { get; set; } /// <summary> /// 实体属性 /// </summary> public Dog DogModel { get; set; } #endregion }
//program
View Code
static void Main(string[] args) { ShallowClone lowClone = new ShallowClone(new Dog { Name = "Dog", Action = "啃骨头" }, "浅拷贝"); ShallowClone lowClone2 = (ShallowClone)lowClone.Clone(); lowClone2.Tag = "浅拷贝克隆"; lowClone2.DogModel.Name = "小狗"; Console.WriteLine(lowClone.Tag+":"+ lowClone.DogModel.Name + lowClone.DogModel.Action); Console.WriteLine(lowClone2.Tag+":" + lowClone2.DogModel.Name + lowClone2.DogModel.Action); DeepClone deepClone = new DeepClone(new Dog { Name = "Dog", Action = "啃骨头" }, "深拷贝"); DeepClone deepClone2 = (DeepClone)deepClone.Clone(); deepClone2.Tag = "深拷贝克隆"; deepClone2.DogModel.Name = "小狗"; Console.WriteLine(deepClone.Tag + ":" + deepClone.DogModel.Name + deepClone.DogModel.Action); Console.WriteLine(deepClone2.Tag + ":" + deepClone2.DogModel.Name + deepClone2.DogModel.Action); Console.Read(); }
//运行结果