Adapter 模式:把不相容變成可合作
Adapter 模式的目的,是把既有介面「包一層」後,轉成使用端想要的介面。常見於舊系統整合或第三方 API 對接。
classDiagram class PaymentProcessor { <<interface>> +processPayment(amount)* boolean } class OldPaymentSystem { +makePayment(value) boolean } class PaymentAdapter { -oldSystem : OldPaymentSystem +processPayment(amount) boolean } PaymentProcessor <|.. PaymentAdapter PaymentAdapter --> OldPaymentSystem : 轉接呼叫 note for PaymentAdapter "將 processPayment()\n轉換為 makePayment()"
使用情境
- 舊系統整合:新系統需要接上舊 API。
- API 版本升級:保留舊介面、導入新實作。
- 第三方套件:不同函式名稱或參數格式轉換。
實作範例

class PaymentProcessor {
processPayment(amount) {
throw new Error('processPayment 必須實作');
}
}
class OldPaymentSystem {
makePayment(value) {
console.log(`Processing payment of $${value} via old system`);
return true;
}
}
class PaymentAdapter extends PaymentProcessor {
constructor() {
super();
this.oldSystem = new OldPaymentSystem();
}
processPayment(amount) {
return this.oldSystem.makePayment(amount);
}
}
const paymentProcessor = new PaymentAdapter();
paymentProcessor.processPayment(100);優點
- 讓不相容介面可以合作
- 提升舊系統可重用性
- 降低整合成本
缺點
- 過度使用會增加間接性
- 類別層次可能變複雜