zoukankan      html  css  js  c++  java
  • C# 原型模式(Prototype)

    理解:通过在类中定义一个Clone方法克隆自己,分为深COPY 和 浅COPY; 现在NET中,继承了ICloneable接口的类都可以重写Clone()方法。

    代码:

    //原型类
        [Serializable]
        public abstract class PrototypeClass
        {
            public string _myValue;

            public string MyValue
            {
                get { return _myValue; }
                set { _myValue = value; }
            }
            public abstract PrototypeClass Clone();
        }

        //浅拷贝
        public class ShallowClone:PrototypeClass
        {
            public ShallowClone(string value)
            {
                this._myValue = value;
            }

            public override PrototypeClass Clone()
            {
                return (PrototypeClass)this.MemberwiseClone();
            }
        }

        //深拷贝
        [Serializable]
        public class DeepClone : PrototypeClass
        {
            public DeepClone(string value)
            {
                this._myValue = value;
            }

            public override PrototypeClass Clone()
            {
                PrototypeClass deepObject;
                MemoryStream memoryStream = new MemoryStream();
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, this);
                memoryStream.Position = 0;
                deepObject = (PrototypeClass)formatter.Deserialize(memoryStream);

                return deepObject;
            }
         }
  • 相关阅读:
    Spark高级数据分析· 2数据分析
    rtsp 学习
    vs code 体验
    RTP 学习
    libev 学习使用
    TS 数据流分析学习
    linux 编程
    times、 time、clock函数说明
    gcc 学习
    2010912 双模机顶盒学习记录
  • 原文地址:https://www.cnblogs.com/kavilee/p/2362429.html
Copyright © 2011-2022 走看看