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;
            }
         }
  • 相关阅读:
    第08讲树
    第11讲简单算法
    【ZOJ1004】Anagrams by Stack
    【ZOJ1649】Rescue
    第10讲并查集
    网站建设与网页制作课件
    获取鼠标的坐标
    asp.net页面的默认回车事件
    NeatUpload的安装使用
    Page methods 执行顺序
  • 原文地址:https://www.cnblogs.com/kavilee/p/2362429.html
Copyright © 2011-2022 走看看