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;
            }
         }
  • 相关阅读:
    面向对象OO第15次作业总结
    面向对象OO第9-11次作业总结
    一文讲完最基本的图算法——图的存储、遍历、最短路径、最小生成树、拓扑排序
    字符串匹配问题的KMP算法
    提问回顾与个人总结
    软工结对作业—最长单词链
    软工第1次个人作业
    软工第0次个人作业
    OO最后一次作业
    JSF生存指南P1
  • 原文地址:https://www.cnblogs.com/kavilee/p/2362429.html
Copyright © 2011-2022 走看看