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

设计模式之桥模式

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

设计模式之桥模式

结构

桥模式
桥模式

说明

Decouple an abstraction from its implementation allowing the two to vary independently.

将一个抽象与实现解耦,以便两者可以独立的变化。

适用条件

  • 不希望在业务和业务的具体实现之间存在固定的绑定关系;
  • 希望类的抽象和实现部分可以扩充, 进而实现不同的抽象接口和实现部分的组合;
  • 复用实现部分。

实现

代码语言:javascript
复制
interface IDrawingApi {

   void DrawCircle(double x, double y, double radius);

}

class DrawingApi1 : IDrawingApi {

   public void DrawCircle(double x, double y, double radius) {
      Console.WriteLine("API1.circle at {0},{1} radius {2}", x, y, radius);
   }

}

class DrawingApi2 : IDrawingApi {

   public void DrawCircle(double x, double y, double radius) {
      Console.WriteLine("API2.circle at {0},{1} radius {2}", x, y, radius);
   }
}

abstract class Shape {

   protected IDrawingApi DrawingApi;

   protected Shape(IDrawingApi drawingApi) {
      this.DrawingApi = drawingApi;
   }

   public abstract void Draw();

   public abstract void ResizeByPercent(double percent);

}

class CircleShape : Shape {

   private readonly double _x;
   private readonly double _y;
   private double _radius;

   public CircleShape(double x, double y, double radius, IDrawingApi drawingApi)
      : base(drawingApi) {
      this._x = x;
      this._y = y;
      this._radius = radius;
   }

   public override void Draw() {
      this.DrawingApi.DrawCircle(this._x, this._y, this._radius);
   }

   public override void ResizeByPercent(double percent) {
      this._radius *= percent;
   }

}

class Program {

   static void Main(string[] args) {
      
      var shapes = new Shape[] {
         new CircleShape(1, 2, 3, new DrawingApi1()),
         new CircleShape(5, 7, 11, new DrawingApi2()),
      };
      
      foreach (var shape in shapes) {
         shape.ResizeByPercent(2.5);
         shape.Draw();
      }

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

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

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

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

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