适配器设计模式详解

发布:2024-09-08 16:02 阅读:16 点赞:0

一、什么是适配器模式?

适配器设计模式充当不兼容接口之间的桥梁,使它们能够无缝协作。它将一个类的接口转换为客户端期望的另一个接口。

二、为什么使用适配器模式?

在实际场景中,系统独立演变,导致组件之间接口不兼容。适配器模式有助于在不修改现有代码的情况下集成这些组件,从而促进了代码的重用性和灵活性。

三、何时使用适配器模式?

适配器模式在以下情况下非常理想:

  1. 集成旧系统与现代系统。
  2. 引入第三方库。
  3. 处理多样化的API。

适配器模式在接口不匹配阻碍互操作性的情况下尤为重要。

四、如何实现适配器模式?

要实现适配器模式,可以按照以下步骤操作:

4.1 创建目标接口

定义一个目标接口,该接口是客户端期望使用的接口。

// 目标接口
public interface IPaymentGateway
{
    void ProcessPayment(double amount);
}

4.2 实现适配者类

适配者类是具有独特接口的现有类。

// 适配者 - GooglePay 网关,具有其独特的接口
public class GooglePayService
{
    public void MakePayment(double amount)
    {
        Console.WriteLine($"GooglePay payment of {amount} processed successfully.");
    }
}

4.3 创建适配器类

适配器类实现目标接口,并包装适配者类的实例,将调用从目标接口映射到适配者接口。

// GooglePayService 的适配器
public class GooglePayAdapter : IPaymentGateway
{
    private readonly GooglePayService _googlePayService;

    public GooglePayAdapter(GooglePayService googlePayService)
    {
        _googlePayService = googlePayService ?? throw new ArgumentNullException(nameof(googlePayService));
    }

    public void ProcessPayment(double amount)
    {
        _googlePayService.MakePayment(amount);
    }
}

4.4 使用适配器

在客户端代码中使用适配器,以实现与适配者的无缝集成。

// 客户端代码
public class PaymentProcessor
{
    public void ProcessPayment(IPaymentGateway paymentGateway, double amount)
    {
        paymentGateway.ProcessPayment(amount);
    }
}
public class Program
{
    public static void Main(string[] args)
    {
        var processor = new PaymentProcessor();

        // 使用适配器集成 GooglePay 支付网关
        var googlePayService = new GooglePayService();
        IPaymentGateway googlePayAdapter = new GooglePayAdapter(googlePayService);
        processor.ProcessPayment(googlePayAdapter, 5000);
    }
}

输出

GooglePay payment of 5000 processed successfully.

五、注意事项

可以使用类似的适配器模式集成其他支付网关。