1.原型模式
用原型实例指定创建对象的实例,并且通过拷贝这些原型创建新的对象。
*原型模式隐藏了创建对象的细节,提高了性能。
*浅复制:被复制对象的所有变量都含有与原来对象相同的值,而且所有对其他对象的引用都指向了原来的对象。
*深复制:被复制对象的引用指向了新的对象,而不是原有的被引用的对象。
*.NET提供IConeable接口下的唯一方法Clone可以便捷的完成原型模式的实现。
2.实例:
namespace 原型模式_浅复制 { class Program { static void Main(string[] args) { Resume a = new Resume("大鸟"); a.SetPersonalInfo("男", "23"); a.SetWorkExperience("2012", "xx公司"); Resume b = (Resume)a.Clone(); b.SetWorkExperience("男", "yy公司"); a.Display(); b.Display();//浅复制下使得引用的复制指向相同空间,a的工作经验被b覆盖 Console.Read(); } } class WorkExperience { private string workDate; public string WorkData { get { return workDate; } set { workDate = value; } } private string company; public string Company { get { return company; } set { company = value; } } } class Resume : ICloneable { private string name; private string sex; private string age; private WorkExperience work; public Resume(string name) { this.name = name; work = new WorkExperience(); } public void SetPersonalInfo(string sex,string age) { this.sex = sex; this.age = age; } public void SetWorkExperience(string workData,string Company) { work.WorkData = workData; work.Company = Company; } public void Display() { Console.WriteLine("{0} {1} {2}", name, sex, age); Console.WriteLine("浅复制:{0} {1}", work.WorkData, work.Company); } public object Clone() { return (object)this.MemberwiseClone(); } } }
此时的输出结果a,b所有细节一致。
namespace 原型模式_深复制 { class Program { static void Main(string[] args) { Resume a = new Resume("大鸟"); a.SetPersonalInfo("男", "23"); a.SetWorkExperience("2012", "xx公司"); Resume b = (Resume)a.Clone(); b.SetWorkExperience("男", "yy公司"); a.Display(); b.Display();//浅复制下使得引用的复制指向相同空间,a的工作经验被b覆盖 Console.Read(); } } class WorkExperience : ICloneable { private string workDate; public string WorkData { get { return workDate; } set { workDate = value; } } private string company; public string Company { get { return company; } set { company = value; } } public Object Clone() { return (object) this.MemberwiseClone(); } } class Resume : ICloneable { private string name; private string sex; private string age; private WorkExperience work; public Resume(string name) { this.name = name; work = new WorkExperience(); } public Resume (WorkExperience work) { this.work = (WorkExperience)work.Clone(); } public void SetPersonalInfo(string sex, string age) { this.sex = sex; this.age = age; } public void SetWorkExperience(string workData, string Company) { work.WorkData = workData; work.Company = Company; } public void Display() { Console.WriteLine("{0} {1} {2}", name, sex, age); Console.WriteLine("深复制:{0} {1}", work.WorkData, work.Company); } public object Clone() { Resume obj = new Resume(this.work); obj.name = this.name; obj.sex = this.sex; obj.age = this.age; return obj; } } }
b中修改工作经验中的属性后a中不受影响。
时间: 2024-11-05 18:42:57