Adapter Pattern
Adapter
是一種結構型設計模式,它允許將一個類的接口轉換為客戶端所期望的另一個接口,用於解決接口不兼容的問題
參與角色
- 目標接口(Target):客戶端所期望的接口,通常是一個接口或抽象類。
- 適配器(Adapter):實現目標接口,並包裝一個被適配者的實例。
- 被適配者(Adaptee):需要被適配的類,它的接口與目標接口不兼容。
範例
假設我們的電子商務平台需要支持 PayPal 和信用卡支付,兩者的接口不同,因此我們需要用適配器模式來統一它們的接口。
目標接口
1 2 3 4
| public interface PaymentGateway { void processPayment(double amount); }
|
被適配者 (Adaptee)
paypal
1 2 3 4 5 6
| public class PayPalPayment { public void makePayment(double amountInUSD) { System.out.println("Processing PayPal payment of $" + amountInUSD); } }
|
Credit Card
1 2 3 4 5 6
| public class CreditCardPayment { public void payWithCard(String cardNumber, double amount) { System.out.println("Processing Credit Card payment of $" + amount + " using card: " + cardNumber); } }
|
適配器
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class PayPalAdapter implements PaymentGateway { private PayPalPayment payPalPayment;
public PayPalAdapter(PayPalPayment payPalPayment) { this.payPalPayment = payPalPayment; }
@Override public void processPayment(double amount) { payPalPayment.makePayment(amount); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class CreditCardAdapter implements PaymentGateway { private CreditCardPayment creditCardPayment; private String cardNumber;
public CreditCardAdapter(CreditCardPayment creditCardPayment, String cardNumber) { this.creditCardPayment = creditCardPayment; this.cardNumber = cardNumber; }
@Override public void processPayment(double amount) { creditCardPayment.payWithCard(cardNumber, amount); } }
|
client
1 2 3 4 5 6 7 8 9 10 11
| public class ECommercePlatform { public static void main(String[] args) { PaymentGateway payPalGateway = new PayPalAdapter(new PayPalPayment()); payPalGateway.processPayment(150.0);
PaymentGateway creditCardGateway = new CreditCardAdapter(new CreditCardPayment(), "1234-5678-9012-3456"); creditCardGateway.processPayment(200.0); } }
|
Output
1 2
| Processing PayPal payment of $150.0 Processing Credit Card payment of $200.0 using card: 1234-5678-9012-3456
|
優點
- 解耦性:客戶端和被適配者之間的耦合度降低,客戶端只需關心目標接口。
- 重用性:可以重用現有的類,不需要修改原始代碼。
- 擴展性:可以根據需要增加新的適配器,擴展系統功能。