设计模式(7/23) - 桥接模式

113 阅读3分钟

桥接模式

1 概述

  • 桥接模式(Bridge Pattern)是一种结构型设计模式,它通过将抽象部分与实现部分分离,使它们可以独立地变化。这种模式涉及到一个抽象类和一个实现类之间通过桥接方法来进行交互,从而实现解耦。
  • 桥接模式通常用于把多种特性组合到一个对象中,使得两者独立变化而不会影响对方。

2 优缺点及应用场景

2.1 优点

  • 1)分离抽象和实现:抽象和实现可以独立扩展,不会相互影响。
  • 2)提高系统的可扩展性:可以更方便地增加或更改抽象和实现部分。
  • 3)符合开闭原则:增加新的抽象部分和实现部分不会影响已有系统。

2.2 缺点

  • 1)增加系统复杂性:由于引入了抽象层和实现层,系统的理解和设计难度增加。

2.3 应用场景

  • 1)希望抽象和实现部分可以独立扩展且不影响对方的情况。
  • 2)一个类存在多个独立变化的维度,且需要通过组合的方式来实现功能的情况。
  • 3)不希望使用继承或因为多层继承结构带来的复杂性时,可以使用桥接模式来简化。

3 结构

  • 1)抽象类(Abstraction):定义抽象部分的接口。
  • 2)扩展抽象类(RefinedAbstraction):扩展抽象类,添加新的功能。
  • 3)实现类接口(Implementor):定义实现部分的接口。
  • 4)具体实现类(ConcreteImplementor):实现实现类接口的具体实现。

4 实现

4.1 UML 类图

桥接模式.jpg

4.2 代码示例

// 创建桥接实现接口
interface DrawAPI {
  public void drawCircle(int radius, int x, int y);
}

// 创建实现了 DrawAPI 接口的实体桥接实现类:红色圆形
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 + "]");
  }
}

// 创建实现了 DrawAPI 接口的实体桥接实现类:绿色圆形
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 + "]");
  }
}

// 使用 DrawAPI 接口创建抽象类 Shape
abstract class Shape {
  protected DrawAPI drawAPI;

  protected Shape(DrawAPI drawAPI) {
    this.drawAPI = drawAPI;
  }

  public abstract void draw();
}

// 创建实现了 Shape 抽象类的实体类:圆形
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 和 DrawAPI 类画出不同颜色的圆
    Shape redCircle = new Circle(100, 100, 10, new RedCircle());
    Shape greenCircle = new Circle(100, 100, 10, new GreenCircle());

    redCircle.draw();
    greenCircle.draw();
  }
}
  • 执行程序,输出结果:
Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[  color: green, radius: 10, x: 100, 100]

5 总结

  • 桥接模式通过将抽象部分与实现部分分离,使它们可以独立地变化,从而实现解耦。它适用于希望抽象和实现部分可以独立扩展且不影响对方的情况。桥接模式提高了系统的可扩展性和灵活性,符合开闭原则,但也增加了系统的复杂性。通过桥接模式,可以更方便地增加或更改抽象和实现部分,实现更复杂的功能。