原型模式

原型模式的理解就是复制,直接上代码:

  public abstract  class  KingPrototype

  {

     public string Id { get; set; }

        public MonkeyKingPrototype(string id)
        {
            this.Id = id;
        }
      
    // 克隆方法,即孙大圣说“变”
       public abstract MonkeyKingPrototype Clone();

  }

/// <summary>
    /// 创建具体原型
    /// </summary>
    public class ConcretePrototype : KingPrototype
    {
        public ConcretePrototype(string id)
            : base(id)
        { }

        /// <summary>
        /// 浅拷贝
        /// </summary>
        /// <returns></returns>
        public override MonkeyKingPrototype Clone()
        {
            // 调用MemberwiseClone方法实现的是浅拷贝,另外还有深拷贝
            return (MonkeyKingPrototype)this.MemberwiseClone();
        }
    }

//使用
// 孙悟空 原型
            KingPrototype prototypeKing = new ConcretePrototype("MonkeyKing");

            // 变一个
            MonkeyKingPrototype cloneMonkeyKing =prototypeKing.Clone() as ConcretePrototype; 
Console.WriteLine("Cloned1:\t"+cloneMonkeyKing.Id);
posted on 2019-03-20 11:25  1老王  阅读(119)  评论(0编辑  收藏  举报