原型模式是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。简单说就是复制对象。
分为浅复制和深复制。
例如找工作时写多分简历。
浅复制实例:
//简历类 class resume : ICloneable { private string name; private string sex; private string age; //private string timeArea; //private string company; private WorkExperience work; public resume(string name){ this.name = name; work = new WorkExperience(); } //设置个人信息 public void setPersonalInfo(string sex,string age) { this.age = age; this.sex = sex; } //设置工作经历 public void setWorkExperience(string timeArea, string company) { work.WorkDate = timeArea; work.Company = company; } //显示 public void Display() { Console.WriteLine("{0} {1} {2}",name ,sex,age ); Console.WriteLine("工作经历 : {0} {1}", work.WorkDate, work.Company); } public Object Clone() { return (Object)this.MemberwiseClone(); } } //工作经历类 class WorkExperience { private string workDate; public string WorkDate { get { return workDate; } set { workDate = value; } } private string company; public string Company { get { return company; } set { company = value; } } } class Program { static void Main(string[] args) { resume a = new resume("大鸟"); a.setPersonalInfo("男","29"); a.setWorkExperience("1990-2000","XXX公司"); resume b = (resume)a.Clone(); b.setWorkExperience("1990-2000", "XYY公司"); resume c = (resume)a.Clone(); c.setPersonalInfo("男","24"); a.Display(); b.Display(); c.Display(); Console.ReadLine(); } }
深复制实例:
//简历类 class resume : ICloneable { private string name; private string sex; private string age; //private string timeArea; //private string company; private WorkExperience work; public resume(string name){ this.name = name; work = new WorkExperience(); } private resume(WorkExperience work) { this.work = (WorkExperience)work.Clone(); } //设置个人信息 public void setPersonalInfo(string sex,string age) { this.age = age; this.sex = sex; } //设置工作经历 public void setWorkExperience(string timeArea, string company) { work.WorkDate = timeArea; work.Company = company; } //显示 public void Display() { Console.WriteLine("{0} {1} {2}",name ,sex,age ); Console.WriteLine("工作经历 : {0} {1}", work.WorkDate, 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; // return (Object)this.MemberwiseClone(); } } //工作经历类 class WorkExperience:ICloneable { private string workDate; public string WorkDate { 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 Program { static void Main(string[] args) { resume a = new resume("大鸟"); a.setPersonalInfo("男","29"); a.setWorkExperience("1990-2000","XXX公司"); resume b = (resume)a.Clone(); b.setWorkExperience("1990-2000", "XYY公司"); resume c = (resume)a.Clone(); c.setPersonalInfo("男","24"); a.Display(); b.Display(); c.Display(); Console.ReadLine(); } }
原文:http://blog.csdn.net/buyingfei8888/article/details/22729541