適配器模式將一個類的接口轉換為客戶期望的另一個接口。生活中最典型的例子是電源適配器:筆記本電池需要直流低壓,插座提供交流高壓,適配器在中間完成轉換,使兩者能夠協作。
Computer — 客戶期望的接口(battery())Power — 現有接口(electric())Computer、組合 Power,在 battery() 中調用 electric()// 目標接口:電腦端
interface Computer { void battery(); }
// 被適配者:電源端
interface Power { void electric(); }
// 具體實現
class ComputerImpl implements Computer {
public void battery() { System.out.println("電池充電中..."); }
}
class PowerImpl implements Power {
public void electric() { System.out.println("輸出 220V 交流電"); }
}
// 適配器:同時實現兩個接口,構造器注入對應端
class Adapter implements Computer, Power {
private Power power;
private Computer computer;
public Adapter(Power power) { this.power = power; }
public Adapter(Computer computer) { this.computer = computer; }
// 電腦視角:需要電池充電 -> 調用電源輸出
@Override public void battery() { if (power != null) power.electric(); }
// 電源視角:需要輸出電能 -> 調用電池充電
@Override public void electric() { if (computer != null) computer.battery(); }
}
public class Client1 {
public static void main(String[] args) {
Computer computer = new ComputerImpl();
Adapter adapter = new Adapter(computer); // 適配器接電腦端
usePower(adapter); // 傳入 Power 接口
}
static void usePower(Power p) { p.electric(); } // 期望 Power
}
// 輸出:電池充電中...
public class Client2 {
public static void main(String[] args) {
Power power = new PowerImpl();
Adapter adapter = new Adapter(power); // 適配器接電源端
useComputer(adapter); // 傳入 Computer 接口
}
static void useComputer(Computer c) { c.battery(); } // 期望 Computer
}
// 輸出:輸出 220V 交流電
| 類型 | 實現方式 | 優點 | 缺點 |
|---|---|---|---|
| 類適配器 | 繼承 Adaptee + 實現 Target | 可覆蓋 Adaptee 方法 | Java 單繼承限制,無法適配 Adaptee 子類 |
| 對象適配器 | 組合 Adaptee 實例 + 實現 Target | 可適配 Adaptee 及其所有子類,符合合成復用原則 | 需委託調用,略繁瑣 |
| 接口適配器 | 實現 Target 默認空方法,子類按需覆蓋 | 避免實現大接口所有方法 | 非標準適配器,屬於門面/抽象類變體 |