设计模式之桥模式

结构

桥模式

说明

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

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

适用条件

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

实现

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();
   }
}