定义:采用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。原型模式允许一个对象再创建另外一个可定制的对象,无需知道任何创建的细节。
举例
用户类中包含一个地址类,实现用户复制
//地址类
public class Address
{
private string province;
private string city;public string Province { get => province; set => province = value; }
public string City { get => city; set => city = value; }public Address(string province, string city)
{
this.province = province;
this.city = city;
}
}
//用户类
public class Customer
{
private string name;
private Address address;public string Name { get => name; set => name = value; }
public Address Address { get => address; set => address = value; }public Customer(string name, Address address)
{
this.name = name;
this.address = address;
}public Customer Clone()
{
Customer clone = null;//使用MemberwiseClone()方法进行浅拷贝,需要强转,是浅克隆
clone = (Customer)MemberwiseClone();//加上复制引用对象,是深克隆
clone.address = new Address(address.Province, address.City);
return clone;
}
}
//客户类(测试类)
class Program
{
static void Main(string[] args)
{
Address address = new Address("HuBei", "Wuhan");
Customer customer = new Customer("ZhangSan", address);Customer newCustomer = customer.Clone();
newCustomer.Name = "LiSi";
newCustomer.Address.Province = "HuNan";
Console.WriteLine(customer.Name);//浅克隆原用户中地址也发生改变,深克隆则不变
Console.WriteLine(customer.Address.Province);
}
}
总结:在需要复制的类中实现一个复制方法,根据引用对象是否也被复制分为浅克隆和深克隆,浅克隆可以直接调用已有的克隆方法(根据语言不同方法细节也不同),在此基础上新建一个引用的对象来替换掉原来的引用对象即为深克隆。
ps:更加方便、全面的深克隆方法可以参考反射、序列化、表达式树等内容。