背景
- 绕过构造器,快速创建已有原型的复制品。
- 复制品可与原型脱勾,独立修改属性或字段。
示例
using static System.Console;
namespace DesignPattern_Prototype
{
public class Resume
{
public string Corp;
public string Location;
public override string ToString()
=> $"\n Corp ={Corp};\n Location ={Location}";
}
public class Person
{
public string Name;
public Resume Resume;
// 浅拷贝:复制值类型的值,复制引用类型的引用
public Person ShallowCopy()
=> (Person)MemberwiseClone();
// 深拷贝:复制所有值,切断引用
public Person DeepCopy()
{
var result = ShallowCopy();
result.Resume = new Resume();
result.Resume.Corp = Resume.Corp;
result.Resume.Location = Resume.Location;
return result;
}
public override string ToString()
=> $"Name ={Name};\nResume ={Resume}";
}
class Demo
{
static void Main(string[] args)
{
var raw = new Person
{
Name = "Zhang San",
Resume = new Resume
{
Corp = "abc",
Location = "manager",
}
};
var shallow = raw.ShallowCopy();
raw.Resume.Corp = "xyz"; // 原稿与浅拷贝同步
var deep = raw.DeepCopy();
deep.Name = "Li Shi";
deep.Resume.Location = "vice president"; // 与原稿异步
WriteLine("The raw is Printing...");
WriteLine(raw);
WriteLine("\nThe shallow copy is Printing...");
WriteLine(shallow);
WriteLine("\nThe deep copy is Printing...");
WriteLine(deep);
ReadKey();
}
}
}
网友评论