原型模式
原型模式,用原型实例指定创建对象的种类, 并且通过拷贝这些原型创建新的对象。
public class WorkExperence : ICloneable
{
public string compnayName;
public string workTime;
public Object Clone()
{
return this.MemberWiseClone();
}
}
public class Person : ICloneable
{
public string name;
public WorkExperence work;
public Person(string name)
{
this.name = name;
work = new WorkExperence();
}
private Person(WorkExperence work)
{
this.work = (WorkExperence)work.Clone();
}
public void SetWork(string companyName,string workTime)
{
this.work.companyName = companyName;
this.work.workTime = workTime;
}
public Object Clone()
{
Person person =new Person(this.work);
person.name = this.name;
return person;
}
}
//使用
public class Program
{
public static void Main()
{
Person p1 = new Person("张三");
p1.SetWork("公司1","2008-2009"); //这个时候p1.name为张三,公司为:公司1
Person p2 = (Person)p1.Clone(); //这个时候p2.name 为张三,公司为: 公司1
p2.setWork("公司2","2009-2010"); //这个时候p2.name 为张三,公司为: 公司2
}
}