设计模式-适配器模式

适配器模式是一种结构型设计模式,用于将一个类的接口转换成客户端所期望的另一个接口。这种模式可以解决由于接口不兼容而无法合作的问题。

在 Java 中,适配器模式可以通过以下步骤实现:

  1. 定义目标接口(Target Interface):这是客户端所期望的接口,也是适配器要实现的接口。

  2. 创建适配器类(Adapter Class):适配器类实现了目标接口,并持有一个对被适配对象的引用。

  3. 创建被适配类(Adaptee Class):被适配类是需要被适配的类,它拥有不兼容的接口。

  4. 在适配器类中实现目标接口的方法:适配器类中的方法将调用被适配类的方法来完成适配。

以下是一个简单的示例代码,演示了适配器模式的实现:

复制代码
// 目标接口
interface Target {
    void request();
}

// 被适配类
class Adaptee {
    void specificRequest() {
        System.out.println("Adaptee's specific request");
    }
}

// 适配器类
class Adapter implements Target {
    private Adaptee adaptee;

    Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

// 客户端代码
public class Main {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request();
    }
}

在上面的示例中,Target 是目标接口,Adaptee 是被适配类,Adapter 是适配器类。适配器类实现了目标接口,并在其方法中调用了被适配类的方法。

当客户端调用适配器的 request() 方法时,实际上是通过适配器间接调用了被适配类的 specificRequest() 方法,从而实现了适配。

相关推荐
数据智能老司机4 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机5 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
使一颗心免于哀伤6 小时前
《设计模式之禅》笔记摘录 - 21.状态模式
笔记·设计模式
数据智能老司机1 天前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机1 天前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴1 天前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
李广坤1 天前
工厂模式
设计模式
幂简集成explinks2 天前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源