橋接模式將抽象部分(Abstraction)與其實作部分(Implementation)解耦,使兩者可以獨立變化。核心在於「組合大於繼承」,避免多維度變化導致的類別組合爆炸。
形狀(圓形、正方形)為抽象維度;繪圖器(彩色、黑白)為實作維度。兩者正交變化,橋接模式完美契合。
interface Printer {
void print(int radius, int x, int y);
}
class ColorPrinter implements Printer {
@Override public void print(int radius, int x, int y) {
System.out.println("Color: radius=" + radius + ", x=" + x + ", y=" + y);
}
}
class BlackPrinter implements Printer {
@Override public void print(int radius, int x, int y) {
System.out.println("Black: radius=" + radius + ", x=" + x + ", y=" + y);
}
}
abstract class Shape {
protected Printer printer; // 橋接引用
protected Shape(Printer p) { this.printer = p; }
public abstract void draw();
}
class Circle extends Shape {
private int x, y, radius;
public Circle(int x, int y, int radius, Printer drawer) {
super(drawer);
this.x = x; this.y = y; this.radius = radius;
}
@Override public void draw() {
printer.print(radius, x, y); // 委派給實作化
}
}
public class Main {
public static void main(String[] args) {
Shape redCircle = new Circle(100, 100, 10, new ColorPrinter());
Shape blackCircle = new Circle(100, 100, 10, new BlackPrinter());
redCircle.draw(); // 輸出 Color 版本
blackCircle.draw(); // 輸出 Black 版本
}
}
兩者結構相似,但意圖不同:
Connection(抽象)+ 各廠商 Driver(實作)。| 優點 | 缺點 |
|---|---|
| 抽象與實作獨立擴充,符合開放封閉原則 | 增加系統理解複雜度,需識別正交維度 |
| 隱藏實作細節,客戶端只依賴抽象 | 不適用於維度高度耦合、難以分離的場景 |
| 減少子類別數量,避免繼承爆炸 | 雙重間接呼叫略增效能開銷(可忽略) |
橋接模式是處理「多維度變化」的利器。關鍵在於識別出系統中穩定的抽象介面與易變的實作維度,透過組合橋接實現雙向獨立演進。