Appearance
桥接模式
意图
将抽象与实现分离,使两者可独立变化。避免「多维度组合」导致类爆炸(如 RedCircle、BlueCircle、RedSquare…)。
类图
Java 示例
java
public interface DrawAPI {
void drawCircle(int x, int y, int radius);
}
public class DrawRed implements DrawAPI {
public void drawCircle(int x, int y, int r) {
System.out.println("red circle @" + x + "," + y + " r=" + r);
}
}
public class DrawBlue implements DrawAPI {
public void drawCircle(int x, int y, int r) {
System.out.println("blue circle @" + x + "," + y + " r=" + r);
}
}
public abstract class Shape {
protected final DrawAPI drawAPI;
protected Shape(DrawAPI api) { this.drawAPI = api; }
public abstract void draw();
}
public class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int r, DrawAPI api) {
super(api);
this.x = x; this.y = y; this.radius = r;
}
public void draw() { drawAPI.drawCircle(x, y, radius); }
}新增颜色只加 DrawAPI 实现,新增形状只加 Shape 子类。
下一节:组合模式