设计模式学习笔记——原型模式(Prototype)
1.特点:在初始化信息不发生变化时考虑。
2.概念:通过复制一个已经存在的实例来创建一个新的实例。被复制的实例被称为原型,这个原型是可定制的。
3.类图:
4.程序实现:
/// <summary> /// 实现了ICloneable接口的简历类 /// </summary> public class Resume:ICloneable { public Resume() { mWorkExperience = new WorkExperience(); } private string mName; private string mSex; private int mAge; private WorkExperience mWorkExperience; public string Name { get { return mName; } set { mName = value; } } public string Sex { get { return mSex; } set { mSex = value; } } public int Age { get { return mAge; } set { mAge = value; } } /// <summary> /// 关联了一个引用类型 /// </summary> public WorkExperience WorkExperience { get { return mWorkExperience; } } public void SetWorkExperience(DateTime startDate, DateTime endDate, string company, string position) { this.mWorkExperience.Company = company; this.mWorkExperience.EndDate = endDate; this.mWorkExperience.StartDate = startDate; this.mWorkExperience.Position = position; } /// <summary> /// 实现ICloneable接口的Clone方法 /// </summary> /// <returns></returns> public object Clone() { // .Net 为我们提供的浅复制对象的方法 return this.MemberwiseClone(); } } /// <summary> /// 工作经历类 /// </summary> public class WorkExperience { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string Company { get; set; } public string Position { get; set; } } [TestMethod] public void TestShallowCopy() { Resume myFirstResume = new Resume { Age = 29, Name = "Kevin Wang", Sex = "男", }; myFirstResume.SetWorkExperience(new DateTime(2006, 7, 1), new DateTime(2007, 7, 1), "My First Company", "Software Engineer"); Resume mySecondResume = (Resume)myFirstResume.Clone(); mySecondResume.SetWorkExperience(new DateTime(2007, 8, 1), new DateTime(2008, 8, 1), "My Second Company", "Software Engineer"); Resume myThirdResume = (Resume)myFirstResume.Clone(); myThirdResume.SetWorkExperience(new DateTime(2008, 8, 1), new DateTime(2009, 8, 1), "My Third Company", "Senior Software Engineer"); Assert.AreEqual("My First Company", myFirstResume.WorkExperience.Company); Assert.AreEqual("My Second Company", mySecondResume.WorkExperience.Company); Assert.AreEqual("My Third Company", myThirdResume.WorkExperience.Company); }