原型模式:用原型實例制定建立對象的種類,而且經過拷貝這些原型建立新的對象。性能
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; } }
客戶端代碼:this
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只是淺表複製,因此結果爲:spa
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(); } }
結果:code