模式介绍

桥接模式是一种结构型设计模式,它可以将抽象部分与实现部分分离,使它们都可以独立地变化。桥接模式通过组合而不是继承来实现功能的扩展。

使用场景

  • 当一个类存在两个独立变化的维度,且这两个维度都需要进行扩展时
  • 当一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性时
  • 当一个类存在多个实现方式时

代码示例

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

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

// 抽象类
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;
    }

    @Override
    public void draw() {
        drawAPI.drawCircle(x, y, radius);
    }
}

优缺点

优点

  • 分离抽象接口及其实现部分
  • 提高了系统的可扩充性
  • 实现细节对客户透明

缺点

  • 增加了系统的理解与设计难度
  • 需要正确地识别出系统中两个独立变化的维度
  • 桥接模式的实现会增加系统的复杂度