标签:prototype 定制 str public ret OLE com clone() stat
原型模式就是从一个对象在创建另一个可定制的对象,而不需要知道任何创建的细节。
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值类型时的坑的示例
标签:prototype 定制 str public ret OLE com clone() stat
原文地址:https://www.cnblogs.com/caiyangcc/p/13047246.html