原型模式模式允许一个对象再创建另外一个可定制的对象,根本无需知道任何如何创建的细节。
原型模式中创建可定制对象的方法有两种深复制和浅复制。浅复制和深复制都是用来获得对象的副本,但是用法不同。C#中有两种类型变量,一种是值类型变量,一种是引用类型变量。当被复制对象内没有引用变量只有值类型变量时用浅复制即可实现复制的目的,而当被复制对象内有引用变量时浅复制只能复制内部对象的引用。浅复制是由系统提供的,而深复制需要在实现浅复制的基础上实现
浅复制:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 原型模式 { 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 workDate,string company) { work.WorkDate = workDate; work.Company = company; } public void Display() { Console.WriteLine("姓名:{0},性别:{1},年龄{2},",this.name,this.sex,this.age); Console.WriteLine("工作经历:{0}",this.work.Company+this.work.WorkDate); } public object Clone() { return (Object)this.MemberwiseClone(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 原型模式 { class Program { static void Main(string[] args) { Resume resume = new Resume("li ming"); resume.SetWorkExperience("2010-2012","IT"); resume.SetPersonalInfo("男","19"); Resume re=(Resume)resume.Clone(); re.SetWorkExperience("2011-2012","服务"); resume.SetWorkExperience("2000-2001", "机械"); resume.Display(); re.Display(); } } }re是由Resume经过浅复制得来的,由于Resume类中有对WorkExperience对象的引用所以当对Resume对象进行浅复制时只是对Resume类中的WorkExperience对象的引用进行了复制。所以不管是resume对象还是复制得到的re对象其内部引用的WorkExperience对象都指向了同一个对象,所以当改变re或resume其中任何一个引用的work对象时另一个都随之变化。所以浅复制对于对象内部引用变量时,所得到的副本对象跟原来对象仍有联系,源对象与副本对象共享一个内部变量的引用。
深复制:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 深度复制 { class Resume { 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 SetExperience(string wordDate,string company) { work.WorkDate = wordDate; work.Company = company; } public void SetPersonalInfo(string sex,string age) { this.sex = sex; this.age = age; } public void Display() { Console.WriteLine("姓名:{0},性别:{1},年龄:{2}",this.name,this.sex,this.age); Console.WriteLine("工作经历:{0}",work.Company+work.WorkDate); } public Object Clone() { Resume obj = new Resume(this.work); obj.name = this.name; obj.age = this.age; obj.sex = this.sex; return obj; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 深度复制 { class Program { static void Main(string[] args) { Resume resume = new Resume("liming"); resume.SetPersonalInfo("男","20"); resume.SetExperience("2010-2011","IT"); Resume re =(Resume)resume.Clone(); re.SetExperience("2000-2001","机械"); resume.Display(); re.Display(); } } }