桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。这种类型的设计模式属于结构型模式,它通过提供抽象化和实现化之间的桥接结构,来实现二者的解耦。这种模式涉及到一个作为桥接的接口,使得实体类的功能独立于接口实现类。这两种类型的类可被结构化改变而互不影响。对于两个独立变化的维度,使用桥接模式再适合不过了。

场景

  • 不希望或者不适合使用继承的场景
  • 接口或者抽象类不稳定的场景
  • 重用性要求较高的场景

实现

代码源于菜鸟教程-设计模式

桥接模式实现的核心点:抽象角色引用实现角色,或者说抽象角色的部分实现是由实现角色完成的

创建桥接实现接口

DrawAPI.java

  1. public interface DrawAPI {
  2. public void drawCircle(int radius, int x, int y);
  3. }

创建实现了实现接口的实体桥接实现类

RedCircle.java

  1. public class RedCircle implements DrawAPI {
  2. @Override
  3. public void drawCircle(int radius, int x, int y) {
  4. System.out.println("Drawing Circle[ color: red, radius: "
  5. + radius +", x: " +x+", "+ y +"]");
  6. }
  7. }

GreenCircle.java

  1. public class GreenCircle implements DrawAPI {
  2. @Override
  3. public void drawCircle(int radius, int x, int y) {
  4. System.out.println("Drawing Circle[ color: green, radius: "
  5. + radius +", x: " +x+", "+ y +"]");
  6. }
  7. }

创建抽象类

Shape.java

  1. public abstract class Shape {
  2. protected DrawAPI drawAPI;
  3. protected Shape(DrawAPI drawAPI){
  4. this.drawAPI = drawAPI;
  5. }
  6. public abstract void draw();
  7. }

创建实现了抽象接口的实体类

Circle.java

  1. public class Circle extends Shape {
  2. private int x, y, radius;
  3. public Circle(int x, int y, int radius, DrawAPI drawAPI) {
  4. super(drawAPI);
  5. this.x = x;
  6. this.y = y;
  7. this.radius = radius;
  8. }
  9. public void draw() {
  10. drawAPI.drawCircle(radius,x,y);
  11. }
  12. }

具体使用

BridgePatternDemo.java

  1. public class BridgePatternDemo {
  2. public static void main(String[] args) {
  3. Shape redCircle = new Circle(100,100, 10, new RedCircle());
  4. Shape greenCircle = new Circle(100,100, 10, new GreenCircle());
  5. redCircle.draw();
  6. greenCircle.draw();
  7. }
  8. }

优点

  • 抽象和实现的分离
  • 优秀的扩充能力
  • 实现细节透明,实现由抽象层进行了封装

Android 中的应用

参考

书籍:《设计模式之禅》、《Android源码设计模式》
技术文章:菜鸟教程-设计模式