设计模式—原型(附带介绍浅拷贝和深拷贝)

时间:2022-10-01 19:37:45

通过拷贝创建新的对象

设计模式—原型(附带介绍浅拷贝和深拷贝)

ColorPrototype是颜色基类(抽象类),ConcteteColorPrototype是具体的父类,他包括两个方法Clone和DeepClone,那就介绍下Clone和DeepClone的区别

Clone: 又叫浅拷贝,MemberwiseClone(),这只能拷贝一层,如果某个属性是引用类型,无法进行真正的拷贝。

DeepClone:是从对象表面到最底端,进行拷贝,是一种完全拷贝。

namespace 大话设计模式
{
     [Serializable]
    public abstract  class ColorPrototype
    {
        /// <summary>
        /// 克隆
        /// </summary>
        /// <returns></returns>
        public abstract ColorPrototype Clone();

        /// <summary>
        /// 深度克隆
        /// </summary>
        /// <returns></returns>
        public abstract ColorPrototype DeepClone();
    }
}
    public class ColorManager
    {
        private Hashtable colors = new Hashtable();

        /// <summary>
        /// 结构
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public ColorPrototype this[string name]
        {
            get { return (ColorPrototype)colors[name]; }
            set { colors.Add(name, value); }
        }
    }
namespace 大话设计模式
{
    [Serializable]
    public class ConcteteColorPrototype : ColorPrototype
    {
        public int red;
        public int green;
        public int blue;

        public Student Student=new Student(){Name = "张三"};

        public ConcteteColorPrototype(int red, int green, int blue)
        {
            this.red = red;
            this.green = green;
            this.blue = blue;
        }
        /// <summary>
        /// 克隆
        /// </summary>
        /// <returns></returns>
        public override ColorPrototype Clone()
        {
            return (ConcteteColorPrototype)this.MemberwiseClone();
        }

        public override ColorPrototype DeepClone()
        {
            MemoryStream memoryStream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(memoryStream, this);
            memoryStream.Position = 0;
           var colorPrototype = (ColorPrototype)formatter.Deserialize(memoryStream);
            return colorPrototype;
        }
    }
      [Serializable]
    public class Student
    {
        public string Name { get; set; }
    }
}