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

设计模式之装饰器模式

作者头像
beginor
发布2020-08-10 11:32:06
3030
发布2020-08-10 11:32:06
举报

设计模式之装饰器模式

结构

装饰器模式
装饰器模式

说明

Attach additional responsibilities to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.

向某个对象动态地添加更多的功能。修饰模式是除类继承外另一种扩展功能的方法。

适用条件

  • 在不影响其他对象的情况下, 以动态且透明的方式添加单个对象的功能;
  • 处理那些可以撤销的功能;
  • 不能采用生成子类的方法扩充时;

实现

代码语言:javascript
复制
interface IWindow {

   void Draw();

   string GetDescription();

}

class SimpleWindow : IWindow {
   
   public void Draw() {
      //
   }

   public string GetDescription() {
      return "Simple window";
   }
}

class WindowDecorator : IWindow {
   
   protected IWindow DecoratedWindow;

   public WindowDecorator(IWindow decoratedWindow) {
      this.DecoratedWindow = decoratedWindow;
   }

   public virtual void Draw() {
      this.DecoratedWindow.Draw();
   }

   public virtual string GetDescription() {
      return "Window decorator";
   }

}

class VerticalScrollbarWindow : WindowDecorator {

   public VerticalScrollbarWindow(IWindow decoratedWindow) : base(    decoratedWindow) {
   }

   public override void Draw() {
      base.Draw();
      this.DrawVerticalScrollbar();
   }

   private void DrawVerticalScrollbar() {
      //
   }

   public override string GetDescription() {
      return this.DecoratedWindow.GetDescription() + ", include vertical     scrollbars";
   }

}

class HorizontalScrollbarWindow : WindowDecorator {

   public HorizontalScrollbarWindow(IWindow decoratedWindow) : base(    decoratedWindow) {
   }

   public override void Draw() {
      base.Draw();
      this.DrawHorizontalScrollbar();
   }

   private void DrawHorizontalScrollbar() {
      //
   }

   public override string GetDescription() {
      return this.DecoratedWindow.GetDescription() + ", include horizontal     scrollbars";
   }

}

class Program {
   
   static void Main(string[] args) {
      IWindow window = new HorizontalScrollbarWindow(new VerticalScrollbarWindow    (new SimpleWindow()));
      Console.WriteLine(window.GetDescription());

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

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

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

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

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