学习笔录——设计模式
原型模式(Prototype)
简介
原型模式就是从一个对象在创建另一个可定制的对象,而不需要知道任何创建的细节。
代码示例
public class WorkDeep : ICloneable
{
public string WorkDate { get; set; }
public string Company { get; set; }
public object Clone()
{
return (object)this.MemberwiseClone();
}
}
public class ResumeDeep : ICloneable
{
public string Name { get; set; }
public int Age { get; set; }
public WorkDeep Work { get; set; }
private ResumeDeep(WorkDeep work)
{
this.Work = (WorkDeep)work.Clone();
}
public ResumeDeep(string name, int age)
{
this.Name = name;
this.Age= age;
this.Work = new WorkDeep();
}
public void SetWork(string company, string workDate)
{
this.Work.WorkDate = workDate;
this.Work.Company = company;
}
public void Display()
{
System.Console.WriteLine(this.Name + this.Age);
System.Console.WriteLine($"{this.Work.Company} {this.Work.Company}");
}
public object Clone()
{
ResumeDeep resume = new ResumeDeep(this.Work);
resume.Name = this.Name;
resume.Age = this.Age;
return resume;
}
}
static void Main(string[] args)
{
// Resume resume = new Resume("hmy");
// resume.SetPersonInfo(21);
// resume.SetWorkExperience("2020","YH");
// Resume resume1 = (Resume)resume.Clone();
// resume1.SetWorkExperience("2019", string.Empty);
ResumeDeep resume3 = new ResumeDeep("hmy", 21);
resume3.SetWork("2020","YH");
ResumeDeep resume4 = (ResumeDeep)resume3.Clone();
resume4.SetWork("2019", string.Empty);
resume3.Display();
resume4.Display();
Console.Read();
}
个人理解,不足之处还请指教。
需要注意值类型和引用类型,在进行复制时的区别,浅复制只会复制值类型,引用类型只会复制引用,比如我在EFCore值类型时的坑的示例