class Program
{
static void Main(string[] args)
{
Resume a = new Resume("大鸟");
a.SetPersonalInfo("男", "29");
a.SetWorkExperience("1998-2000", "xx公司");
Resume b = (Resume)a.Clone();
b.SetWorkExperience("1998-2000", "hh公司");
Resume c = (Resume)a.Clone();
c.SetWorkExperience("1998-2000", "pp公司");
a.Display();
b.Display();
c.Display();
Console.ReadKey();
}
}
class WorkExperence: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 Resume:ICloneable
{
private string name;
private string sex;
private string age;
private WorkExperence work;
public Resume(string _name)
{
this.name = _name;
work = new WorkExperence();
}
//此处也不再采用构造函数开始拷贝引用类型
//private Resume(WorkExperence _work)
//{
// this.work = (WorkExperence)_work.Clone();
//}
public void SetPersonalInfo(string _sex,string _age)
{
this.sex = _sex;
this.age = _age;
}
public void SetWorkExperience(string _timeArea,string _company)
{
work.WorkDate = _timeArea;
work.Company = _company;
}
public void Display()
{
Console.WriteLine("{0} {1} {2}", this.name, this.sex, this.age);
Console.WriteLine("工作经历:{0},{1}", this.work.WorkDate, this.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;
//注:此处未采用《大话设计模式》的拷贝方式,而采用先拷贝该类的值类型,在拷贝引用类型的值类型,以此类推
//直到最深层全部拷贝为止,此例子仅两层。 采用这种方式代码简单易懂,效率高
object obj = this.MemberwiseClone();
(obj as Resume).work = (WorkExperence)this.work.Clone();
return obj;
//return (object)this.MemberwiseClone();
}
}