设计模式之原型模式
原型模式(Prototype)是一种通过定义一个原型对象,然后通过复制该原型对象来创建新对象的设计模式。这种方式可以避免直接使用类的实例化操作,从而隐藏对象创建的细节并提升性能。
基本实现:
abstract class Prototype
{
private string id;
public Prototype(string id)
{
this.id = id;
}
public string Id
{
get
{
return id;
}
}
public abstract Prototype Clone();
}
class ConcretePrototype1 : Prototype
{
public ConcretePrototype1(string id) : base(id)
{
}
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
}
}
浅拷贝示例:
static void Main(string[] args)
{
ConcretePrototype1 p1 = new ConcretePrototype1("I");
ConcretePrototype1 C1 = (ConcretePrototype1)p1.Clone();
Console.WriteLine("Cloned:{0}", C1.Id);
Console.Read();
}
深拷贝实现:
class WorkExperience : ICloneable
{
public string WorkData { get; set; }
public string Company { get; set; }
public object Clone()
{
return this.MemberwiseClone();
}
}
class Resume : ICloneable
{
private string name;
private string sex;
private string age;
private WorkExperience work;
public Resume(string name)
{
this.name = name;
this.work = new WorkExperience();
}
private Resume(WorkExperience work)
{
this.work = (WorkExperience)work.Clone();
}
public void SetPersonalInfo(string sex, string age)
{
this.sex = sex;
this.age = age;
}
public void SetWorkExperience(string workData, string company)
{
work.Company = company;
work.WorkData = workData;
}
public void Display()
{
Console.WriteLine("{0},{1},{2}", name, sex, age);
Console.WriteLine("工作经历:{0},{1}", work.WorkData, work.Company);
}
public object Clone()
{
Resume obj = new Resume(work);
obj.name = this.name;
obj.sex = this.sex;
obj.age = this.age;
return obj;
}
}
深拷贝测试:
static void Main(string[] args)
{
Resume a = new Resume("我是谁");
a.SetPersonalInfo("男", "29");
a.SetWorkExperience("2018-11-1", "杭州德川");
Resume b = (Resume)a.Clone();
b.SetWorkExperience("2020-2-09", "dahua");
Resume c = (Resume)a.Clone();
c.SetPersonalInfo("女", "23");
c.SetWorkExperience("2021-9-08", "kaba");
a.Display();
b.Display();
c.Display();
Console.Read();
}