適配器模式(Adapter Pattern) 是一種結構型設計模式,它允許將不兼容的接口轉換為客戶端期望的接口,使原本由于接口不兼容而不能一起工作的類可以協同工作。
一、核心思想
- 將一個類的接口轉換成客戶期望的另一個接口
- 使原本因接口不匹配而無法一起工作的類能夠一起工作
- 屬于"包裝器"(Wrapper)設計模式的一種
二、適用場景
1.需要使用現有類,但其接口與需求不匹配
2.想要復用一些現有的子類,但這些子類缺少一些公共功能
3.需要與多個不兼容的接口或庫一起工作
三、適配器模式在 C# 中的實現
1. 類適配器(使用繼承)
// 目標接口(客戶端期望的接口)
public interface ITarget
{void Request();
}// 被適配者(現有的不兼容類)
public class Adaptee
{public void SpecificRequest(){Console.WriteLine("Adaptee's SpecificRequest() called");}
}// 類適配器(通過多重繼承實現)
public class ClassAdapter : Adaptee, ITarget
{public void Request(){// 將目標接口方法轉換為被適配者的方法base.SpecificRequest();}
}// 客戶端代碼
class Program
{static void Main(){ITarget target = new ClassAdapter();target.Request(); // 輸出: Adaptee's SpecificRequest() called}
}
2. 對象適配器(使用組合)
// 目標接口
public interface ITarget
{void Request();
}// 被適配者
public class Adaptee
{public void SpecificRequest(){Console.WriteLine("Adaptee's SpecificRequest() called");}
}// 對象適配器(通過組合實現)
public class ObjectAdapter : ITarget
{private readonly Adaptee _adaptee;public ObjectAdapter(Adaptee adaptee){_adaptee = adaptee;}public void Request(){// 將請求委托給被適配者_adaptee.SpecificRequest();}
}// 客戶端代碼
class Program
{static void Main(){Adaptee adaptee = new Adaptee();ITarget target = new ObjectAdapter(adaptee);target.Request(); // 輸出: Adaptee's SpecificRequest() called}
}
四、實際應用示例
示例:第三方支付系統適配
// 目標接口(系統期望的支付接口)
public interface IPaymentGateway
{void ProcessPayment(decimal amount);
}// 第三方支付系統(不兼容的接口)
public class ThirdPartyPaymentProcessor
{public void MakePayment(double amount){Console.WriteLine($"Processing payment of amount: {amount}");}
}// 適配器
public class PaymentAdapter : IPaymentGateway
{private readonly ThirdPartyPaymentProcessor _processor;public PaymentAdapter(ThirdPartyPaymentProcessor processor){_processor = processor;}public void ProcessPayment(decimal amount){// 將decimal轉換為double以適應第三方系統double convertedAmount = (double)amount;_processor.MakePayment(convertedAmount);}
}// 客戶端代碼
class Program
{static void Main(){var thirdPartyProcessor = new ThirdPartyPaymentProcessor();IPaymentGateway paymentGateway = new PaymentAdapter(thirdPartyProcessor);paymentGateway.ProcessPayment(99.99m);// 輸出: Processing payment of amount: 99.99}
}
五、適配器模式的優缺點
優點
- 單一職責原則:將接口轉換代碼從業務邏輯中分離
- 開閉原則:可以引入新的適配器而不影響現有代碼
- 提高了類的復用性
缺點
- 增加了系統復雜性(需要引入新的類和接口)
- 在某些情況下,過度使用適配器會使系統變得難以維護
六、適配器模式與其他模式的關系
-
與外觀模式:適配器包裝一個類,而外觀模式包裝整個子系統
-
與橋接模式:兩者都旨在將抽象與實現解耦,但適配器關注已有接口的兼容性,橋接模式關注提前設計
-
與裝飾器模式:適配器提供不同的接口,裝飾器提供擴展功能而不改變接口
七、最佳實踐
- 當接口不兼容但功能相似時使用適配器模式
- 優先使用對象適配器(組合方式)而非類適配器(繼承方式),因為更靈活
- 考慮使用依賴注入來管理適配器的生命周期
- 為適配器編寫單元測試以確保轉換邏輯正確
適配器模式在C#中特別適用于集成遺留系統、第三方庫或處理接口不匹配的情況,是構建可擴展、可維護系統的重要工具。