设计模式-结构型模式-适配器模式

0 引言

结构型模式(Structural Pattern)关注如何将现有类或对象组织在一起形成更加强大的结构。

1 适配器模式

适配器模式(Adapter Pattern):将一个接口转换成客户希望的另一个接口,使接口不兼容的那些类可以一起工作,其别名为包装器(Wrapper)。适配器模式既可以作为类结构型模式,也可以作为对象结构型模式。

复制代码
//首先,我们定义一个接口Target,这是客户端期望的接口:
public interface Target {
    void request();
}

//然后,我们有一个类Adaptee,它的接口与Target接口不兼容:
public class Adaptee {
    public void specificRequest() {
        System.out.println("Called specificRequest()");
    }
}
接下来,我们创建一个适配器Adapter,它实现了Target接口,并包含一个Adaptee对象。在Adapter的request()方法中,我们调用Adaptee的specificRequest()方法,从而实现了对Adaptee接口的包装:
public class Adapter implements Target {
    private Adaptee adaptee;

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

    @Override
    public void request() {
        adaptee.specificRequest();
        //TODO 做数据转换,拿到adptee的数据,转换为client需要的
    }
}

最后,我们在客户端代码中使用适配器模式:
public class Client {
    public static void main(String[] args) {
        Target target = new Adapter(new Adaptee());
        target.request();
    }
}
相关推荐
逍遥德1 小时前
MQTT教程详解-05.SpringBoot集成mqtt client 性能分析
java·spring boot·spring·mt
云烟成雨TD1 小时前
Spring AI 1.x 系列【54】Retry 机制分析
java·人工智能·spring
weixin_523185321 小时前
Collections.unmodifiableMap详解:真的不可修改吗?
java·linux·前端
点燃大海1 小时前
SpringAI构建智能体
java·spring boot·spring·springai智能体
xier_ran1 小时前
【infra之路】02_RadixAttention与KV_Cache管理
java·spring boot·spring
黑马师兄2 小时前
RAG混合检索深度解析:让AI真正找到你要的内容
java·人工智能·ai·agent·rag·ai-native
码客日记2 小时前
Spring Boot 配置文件敏感信息加密(Jasypt 企业级完整方案)
java·spring boot·git
凡人叶枫2 小时前
Effective C++ 条款04:确定对象被使用前已先被初始化
java·linux·开发语言·c++·嵌入式开发
极客先躯2 小时前
高级java每日一道面试题-2026年02月01日-实战篇[Docker]-Docker Volume 的生命周期管理是怎样的?
java·运维·docker·容器·持久化·架构图·容器卷
NE_STOP3 小时前
Raft算法处理细节
java