1,定義
原型模式:用原型實(shí)例指定創(chuàng)建對(duì)象的種類,并且通過拷貝這些原型創(chuàng)建新對(duì)象
2,基本代碼
abstract class Prototype
{
private string id;
// Constructor
public Prototype(string id)
{
this.id = id;
}
// Property
public string Id
{
get { return id; }
}
public abstract Prototype Clone();
}
class ConcretePrototype1 : Prototype
{
// Constructor
public ConcretePrototype1(string id)
: base(id)
{
}
public override Prototype Clone()
{
// Shallow copy
return (Prototype)this.MemberwiseClone();
}
}
class ConcretePrototype2 : Prototype
{
// Constructor
public ConcretePrototype2(string id)
: base(id)
{
}
public override Prototype Clone()
{
// Shallow copy
return (Prototype)this.MemberwiseClone();
}
}
// 調(diào)用
static void Main(string[] args)
{
ConcretePrototype1 p1 = new ConcretePrototype1("I");
ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
Console.WriteLine("Cloned: {0}", c1.Id);
ConcretePrototype2 p2 = new ConcretePrototype2("II");
ConcretePrototype2 c2 = (ConcretePrototype2)p2.Clone();
Console.WriteLine("Cloned: {0}", c2.Id);
// Wait for user
Console.Read();
}
3,簡單實(shí)現(xiàn)
//簡歷
class Resume : ICloneable
{
private string name;
private string sex;
private string age;
private WorkExperience work;
public Resume(string name)
{
this.name = name;
work = new WorkExperience();
}
private Resume(WorkExperience work)
{
this.work = (WorkExperience)work.Clone();
}
//設(shè)置個(gè)人信息
public void SetPersonalInfo(string sex, string age)
{
this.sex = sex;
this.age = age;
}
//設(shè)置工作經(jīng)歷
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("工作經(jīng)歷:{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;
}
}
//工作經(jīng)歷
class WorkExperience : 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();
}
}
// 調(diào)用
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-2006", "YY企業(yè)");
Resume c = (Resume)a.Clone();
c.SetWorkExperience("1998-2003", "ZZ企業(yè)");
a.Display();
b.Display();
c.Display();
Console.Read();
}
4,關(guān)于原型模式的思考
1,深復(fù)制,淺復(fù)制
淺復(fù)制:被復(fù)制對(duì)象的所有的變量都含有與原來的對(duì)象相同的值,而所有的對(duì)其他對(duì)象的引用都指向原來的對(duì)象
深復(fù)制:把引用對(duì)象的變量指向復(fù)制過的新對(duì)象,而不是原有的被引用的對(duì)象
2,System的ICloneable()接口
MemberwiseClone() 方法:如果字段是值類型的,則對(duì)該字段進(jìn)行逐位復(fù)制,如果字段是引用類型,則復(fù)制引用但是不復(fù)制引用對(duì)象,因此,原有對(duì)象及其復(fù)本引用同一對(duì)象