原型模式简介
用原型实例指定创建对象的种类并且通过拷贝这些原型创建新的对象,是用于创建重复的对象,同时又能保证性能。该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。
原型模式:
- 动态获取一个类的运行状态,避免耗时new的实例化;
- 做对象copy
原型模式的copy只是一个浅copy,它并不能copy引用类型 - 深copy实现
让引用类型都实现一个Clone方法,从而手工实现这个深copy;
C# BinaryFormatter通过二进制将对象的图进化序列化;
与通过对一个类进行实例化来构造新对象不同的是,原型模式是通过拷贝一个现有对象生成新对象的。浅拷贝实现 Cloneable,重写,深拷贝是通过实现 Serializable 读取二进制流。 | |
---|---|
C# 原型模式 Demo
using System;
using System.Collections.Generic;
namespace Prototype
{
class Program
{
static void Main(string[] args)
{
var person = new Person()
{
Name = "jack",
Age = 20,
Address = new Address()
{
Province = "陕西",
City = "渭南"
}
};
var person2 = (Person)person.Clone();
person2.Address = (Address)person.Address.Clone();
}
}
/// <summary>
/// Prototype抽象类
/// </summary>
public abstract class Prototype
{
public abstract object Clone();
}
/// <summary>
/// Person类
/// </summary>
public class Person : Prototype
{
private string name;
private int age;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public int Age
{
get
{
return age;
}
set
{
age = value;
}
}
public Address Address
{
get;set;
}
public Person()
{
Console.WriteLine("当前构造函数被执行:{0}", DateTime.Now);
}
public override object Clone()
{
return this.MemberwiseClone();
}
}
/// <summary>
/// 地址类
/// </summary>
public class Address : Prototype
{
public string City
{
get => default;
set
{
}
}
public string Province
{
get => default;
set
{
}
}
public override object Clone()
{
return this.MemberwiseClone();
}
}
}
更多: