適配器模式 將一個類的介面轉換成客戶端期望的另一個介面,讓原本介面不相容的類別能夠合作。又稱「包裝器模式」。
// 被適配者:既有介面
class Adaptee {
public void specificRequest() {
System.out.println("Hello, I am from Adaptee!");
}
}
// 目標介面:客戶端期望
interface Target {
void request();
}
// 適配器:實作 Target,委派 Adaptee
class Adapter implements Target {
private Adaptee adaptee = new Adaptee();
@Override
public void request() {
adaptee.specificRequest();
}
}
// 客戶端
public class Client {
public static void main(String[] args) {
Target target = new Adapter();
target.request(); // 輸出: Hello, I am from Adaptee!
}
}
當抽象化與實作化都可能獨立變化時,橋接模式將兩者解耦,使其能各自擴充而不互相影響。避免繼承爆炸(如:形狀 × 繪圖 API = 組合爆炸)。
// 實作化介面
interface DrawingAPI {
void drawCircle(double x, double y, double radius);
}
// 具體實作化 1
class DrawingAPI1 implements DrawingAPI {
public void drawCircle(double x, double y, double radius) {
System.out.printf("API1.circle at %f:%f radius %f%n", x, y, radius);
}
}
// 具體實作化 2
class DrawingAPI2 implements DrawingAPI {
public void drawCircle(double x, double y, double radius) {
System.out.printf("API2.circle at %f:%f radius %f%n", x, y, radius);
}
}
// 抽象化角色
interface Shape {
void draw(); // 低層:委派實作化
void resizeByPercentage(double pct); // 高層:抽象化特有邏輯
}
// 修正抽象化
class CircleShape implements Shape {
private double x, y, radius;
private DrawingAPI drawingAPI;
public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) {
this.x = x; this.y = y; this.radius = radius; this.drawingAPI = drawingAPI;
}
@Override
public void draw() {
drawingAPI.drawCircle(x, y, radius); // 委派實作化
}
@Override
public void resizeByPercentage(double pct) {
radius *= pct; // 抽象化層邏輯
}
}
// 客戶端
public class BridgeDemo {
public static void main(String[] args) {
Shape[] shapes = {
new CircleShape(1, 2, 3, new DrawingAPI1()),
new CircleShape(5, 7, 11, new DrawingAPI2())
};
for (Shape s : shapes) {
s.resizeByPercentage(2.5);
s.draw();
}
}
}
| 維度 | 適配器模式 | 橋接模式 |
|---|---|---|
| 意圖 | 事後補救:讓不相容介面能合作 | 事先規劃:分離抽象與實作,支援獨立演化 |
| 關係 | 適配器「包裝」被適配者 | 抽象化「持有」實作化參考 |
| 耦合度 | 降低客戶端與被適配者耦合 | 降低抽象化與實作化耦合 |
| 典型場景 | 整合第三方庫、舊系統遷移 | 跨平台 GUI、驅動程式架構、策略切換 |
適配器模式解決「介面不匹配」的整合問題;橋接模式解決「多維度變化」的架構問題。實務中常搭配使用:橋接定義架構骨幹,適配器處理外部系統接入。掌握兩者精髓,能顯著提升系統的擴充性與維護性。