Skip to content

桥接模式

基础概念

什么是桥接模式?

答案: 桥接模式(Bridge Pattern)将抽象部分与实现部分分离,使它们都可以独立地变化。

使用场景

  • 不希望在抽象和实现之间有固定的绑定关系
  • 抽象和实现都应该可以通过子类扩展

优点

  • 分离抽象和实现
  • 提高可扩展性
  • 实现细节对客户透明

缺点

  • 增加系统理解难度

实现方式

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

// 具体实现A
public class RedCircle implements DrawAPI {
    @Override
    public void drawCircle(int x, int y, int radius) {
        System.out.println("红色圆形");
    }
}

// 具体实现B
public class GreenCircle implements DrawAPI {
    @Override
    public void drawCircle(int x, int y, int radius) {
        System.out.println("绿色圆形");
    }
}

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

// 使用
Shape redCircle = new Circle(100, 100, 10, new RedCircle());
Shape greenCircle = new Circle(200, 200, 20, new GreenCircle());
redCircle.draw();
greenCircle.draw();

练习题

  1. 桥接模式和适配器模式的区别?
  2. 桥接模式的应用场景?
  3. JDBC驱动如何体现桥接模式?

Released under the MIT License.