前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >设计模式之原型模式

设计模式之原型模式

作者头像
beginor
发布2020-08-10 14:24:49
2570
发布2020-08-10 14:24:49
举报

设计模式之原型模式

结构

原型模式
原型模式

说明

Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

适用条件

原型模式多用于创建复杂的或者耗时的实例,因为这种情况下,复制一个已经存在的实例使程序运行更高效;或者创建值相等,只是命名不一样的同类数据。

实现

代码语言:javascript
复制
abstract class Prototype : ICloneable {

   public abstract int X {
      get;
      set;
   }

   public abstract void PrintX();

   public abstract object Clone();

}

class PrototypeImpl : Prototype {

   private int _x;

   public override int X {
      get {
         return this._x;
      }
      set {
         this._x = value;
      }
   }

   public PrototypeImpl(int x) {
      this._x = x;
   }

   public override void PrintX() {
      Console.WriteLine("value : {0}", this.X);
   }

   public override object Clone() {
      return new PrototypeImpl(this._x);
   }
}

class Program {

   static void Main(string[] args) {
      Prototype prototype = new PrototypeImpl(1000);

      for (int i = 1; i < 10; i++) {
         var tempotype = (Prototype)prototype.Clone();

         // Usage of values in prototype to derive a new value.
         tempotype.X = tempotype.X * i;
         tempotype.PrintX();
      }

      Console.ReadKey();
   }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 设计模式之原型模式
    • 结构
      • 说明
        • 适用条件
          • 实现
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档