zoukankan      html  css  js  c++  java
  • 设计模式—原型(附带介绍浅拷贝和深拷贝)

    通过拷贝创建新的对象

    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; }
        }
    }
  • 相关阅读:
    利用Python对文件进行批量重命名
    应用程序处于中断模式-设置方法
    idea http请求的插件(测试接口方便)
    ajax 分页(jquery分页插件pagination) 小例3
    JProfile 9.2 linux安装及windows客户端远程监控
    serializeObject 的应用
    linux下 mysql数据库的备份和还原
    ajax 分页(jquery分页插件pagination) 小例2
    bootstrapTable 应用小例(收索)
    表格 td中,取checkbox后几位值
  • 原文地址:https://www.cnblogs.com/cainiaoguoshi/p/3454217.html
Copyright © 2011-2022 走看看