原型模式:
在A a=new A();A b=a;是传引用而不是传值引用。
我们在A中加入clone()方法,使其传值。这就是原型
//原型类
abstract class Prototype
{
private string id;
public Prototype(string id)
{
this.id = id;
}
public string Id
{
get { return id; }
}
//抽象类的关键是具有此虚方法
public abstract Prototype Clone();
}
//具体原型类
class ConcretePrototypel:Prototype
{
public ConcretePrototypel(string id)
: base(id)
{ }
//实现浅克隆,复制值类型,复制引用,但不复制引用对象
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
}
}
Program:
ConcretePrototypelp1 = new ConcretePrototypel("i");
ConcretePrototypel c1 = (ConcretePrototypel)p1.Clone();
Console.WriteLine("cloned:{0}",c1.Id);
实现深克隆:
//工作经历
class WorkExperience
{
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();
}
}
简历:
classResume
{
private string name;
private string sex;
private string age;
private WorkExperience work;
public Resume(string name)
{
this.name = name;
work = new WorkExperience();
}
//提供clone方法的私有构造函数,以便克隆工作经历数据
privateResume(WorkExperience work)
{
this.work = (WorkExperience)work.Clone();
}
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}",name,sex,age);
Console.WriteLine("工作经历:{0} {1}",work.WorkDate,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;
}
}
Program:
class Program
{
static void
{
Resume a = new Resume("大鸟");
a.SetPersonalInfo("男","29");
a.SetWorkExperience("1998-2000","xxx公司");
Resume b = (Resume)a.Clone();
b.SetWorkExperience("1998-2006","yyy公司");
a.Display();
b.Display();
Console.ReadKey();
}
}