设计模式 六月 03, 2021

桥接模式

文章字数 3.4k 阅读约需 3 mins. 阅读次数 0

桥接模式

解决问题

在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。

方案

把这种多角度分类分离出来,让它们独立变化,减少它们之间耦合。

结构

桥接模式

  • 抽象类(Abstraction):定义抽象类的接口,维护一个指向Implementor类型对象的指针
  • 扩充抽象类(RefinedAbstraction):扩充由Abstraction定义的接口
  • 实现类接口(Implementor):定义实现类的接口,该接口不一定要与 Abstraction的接口完全一致;事实上这两个接口可以完全不同。一般来讲, Implementor接口仅提供基本操作,而 Abstraction则定义了基于这些基本操作的较高层次的操作
  • 具体实现类(ConcreteImplementor):实现Implementor接口并定义它的具体实现

适用性

  • 你不希望在抽象和他的实现部分之间有一个固定的邦定关系,如在程序的运行时刻实现部分应该可以被选择或者切换。
  • 类的抽象以及他的视像都可以通过生成子类的方法加以扩充。这时bridge模式使你可以对不同的抽象接口和实现部分进行组合,并对他们进行扩充。
  • 对一个抽象的实现部分的修改应该对客户不产生影响,即客户的代码不需要重新编译。
  • 你想对客户完全隐藏抽象的实现部分。
  • 你想在多个实现间共享实现,但同时要求客户并不知道这一点。

优缺点

优点

  • 分离接口及其实现部分: 一个实现未必不变地绑定在一个接口上。抽象类的实现可以在运行时刻进行配置,一个对象甚至可以在运行时刻改变它的实现。
  • 提高可扩充性: 你可以独立地对Abstraction和Implementor层次结构进行扩充。
  • 实现细节对客户透明

缺点

增加系统的理解与设计难度

经典实现

桥接模式_Demo

// 实现类接口
public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}
// 具体实现类
public class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: red, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}

// 具体实现类
public class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: "
         + radius +", x: " +x+", "+ y +"]");
   }
}

// 抽象类 维护一个指向Implementor类型对象的指针
public abstract class Shape {
   protected DrawAPI drawAPI;
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();  
}

// 扩充抽象类
public class Circle extends Shape {
   private int x, y, radius;
 
   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }
 
   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}

//
public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
 
      redCircle.draw();
      greenCircle.draw();
   }
}
0%