标签:style blog http color ar strong sp div 2014
原型模式:用原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。
public class Resume : ICloneable { private string sex; private string age; private string timeArea; private string company; //设置个人信息 public void SetPersonalInfo(string sex, string age) { this.sex = sex; this.age = age; } //设置工作经历 public void SetWorkExprience(string timeArea, string company) { this.timeArea = timeArea; this.company = company; } //显示 public void Display() { Console.WriteLine("个人信息:{0} {1} {2}", name, sex, age); Console.WriteLine("工作经验:{0} {1}", timeArea, company); } //克隆 public Object Clone() { return (Object)this.MemberwiseClone(); } }
public class Resume : ICloneable { private string name; private string sex; private string age; private WorkExperience workExperience; public Resume(string name) { this.name = name; this.workExperience = new WorkExperience(); } //设置个人信息 public void SetPersonalInfo(string sex, string age) { this.sex = sex; this.age = age; } //设置工作经历 public void SetWorkExprience(string timeArea, string company) { workExperience.WorkDate = timeArea; workExperience.Company = company; } //显示 public void Display() { Console.WriteLine("个人信息:{0} {1} {2}", name, sex, age); Console.WriteLine("工作经验:{0} {1}", workExperience.WorkDate, workExperience.Company); } //克隆 public Object Clone() { return (Object)this.MemberwiseClone(); } } /// <summary> /// 工作经验类 /// </summary> class WorkExperience { public string WorkDate { get; set; } public string Company { get; set; } }
客户端代码:
Resume r = new Resume("张三"); r.SetPersonalInfo("男", "25"); r.SetWorkExprience("2010", "嘻嘻"); var rr = (Resume)r.Clone(); rr.SetWorkExprience("2014", "xx嘻"); r.Display(); rr.Display(); Console.ReadLine();
因为 MemberwiseClone只是浅表复制,所以结果为:
public class Resume : ICloneable { private string name; private string sex; private string age; private WorkExperience workExperience; public Resume(string name) { this.name = name; this.workExperience = new WorkExperience(); } public Resume(WorkExperience workExperience) { this.workExperience = (WorkExperience)workExperience.Clone(); } //设置个人信息 public void SetPersonalInfo(string sex, string age) { this.sex = sex; this.age = age; } //设置工作经历 public void SetWorkExprience(string timeArea, string company) { workExperience.WorkDate = timeArea; workExperience.Company = company; } //显示 public void Display() { Console.WriteLine("个人信息:{0} {1} {2}", name, sex, age); Console.WriteLine("工作经验:{0} {1}", workExperience.WorkDate, workExperience.Company); } //克隆 public Object Clone() { Resume r = new Resume(this.workExperience); r.name = this.name; r.sex = this.sex; r.age = this.age; return r; } } /// <summary> /// 工作经验类 /// </summary> public class WorkExperience { public string WorkDate { get; set; } public string Company { get; set; } public Object Clone() { return (Object)this.MemberwiseClone(); } }
结果:
标签:style blog http color ar strong sp div 2014
原文地址:http://www.cnblogs.com/wzq806341010/p/4016411.html