原型模式(Prototype):用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。原型模式其实就是从一个对象再创建另一个可以定制的对象,而且不需要知道任何创建的细节。
浅复制:被复制对象的所有变量都含有与原来的对象相同的值,而所有的其它的对象的引用都仍然指向原来的对象。
深复制:把引用对象的变量指向复制过来的新对象,而不是原有对象的引用。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace StuDesignMode.Prototype
- {
- /// <summary>
- /// 工作经历
- /// </summary>
- class WorkExperience:ICloneable
- {
- /// <summary>
- /// 时间段
- /// </summary>
- public string WorkDate { get; set; }
- /// <summary>
- /// 公司名称
- /// </summary>
- public string Company { get; set; }
- public object Clone()
- {
- return this.MemberwiseClone();
- }
- }
- /// <summary>
- /// 简历
- /// </summary>
- class Resume : ICloneable
- {
- public string Name { get; set; }
- public string Sex { get; set; }
- public string Age { get; set; }
- public WorkExperience workExperience { get; set; }
- public Resume(string name)
- {
- this.Name = name;
- this.workExperience = new WorkExperience();
- }
- private Resume(WorkExperience work)
- {
- this.workExperience = (WorkExperience)work.Clone();
- }
- /// <summary>
- /// 设置个人信息
- /// </summary>
- /// <param name="sex"></param>
- /// <param name="age"></param>
- public void SetPersonlInfo(string name,string sex, string age)
- {
- this.Name = name;
- this.Sex = sex;
- this.Age = age;
- }
- /// <summary>
- /// 设置工作经历
- /// </summary>
- /// <param name="workDate"></param>
- /// <param name="company"></param>
- public void setWorkExperience(string workDate, string company)
- {
- this.workExperience.WorkDate = workDate;
- this.workExperience.Company = company;
- }
- /// <summary>
- /// 显示
- /// </summary>
- public void Display()
- {
- Console.WriteLine("{0} {1} {2}", this.Name, this.Sex, this.Age);
- Console.WriteLine("工作经历:{0} {1}", workExperience.WorkDate, workExperience.Company);
- }
- public object Clone()
- {
- Resume resume = new Resume(this.workExperience);
- resume.Name = this.Name;
- resume.Age = this.Age;
- resume.Sex = this.Sex;
- return resume;
- }
- }
- public class ClientTest
- {
- static void Main(string[] args)
- {
- Resume liming = new Resume("李明");
- liming.SetPersonlInfo("李明", "男", "22岁");
- liming.setWorkExperience("2005年 --- 2007年 ", "IBM");
- liming.Display();
- Resume wanghao = liming.Clone() as Resume;
- wanghao.SetPersonlInfo("王浩", "男", "24岁");
- wanghao.setWorkExperience("2005年 --- 2008年 ", "Sun");
- wanghao.Display();
- }
- }
- }