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

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();
    }
}
相关推荐
东离与糖宝12 小时前
Java 26+Spring Boot 3.5,微服务启动从3秒压到0.8秒
java·人工智能
禹中一只鱼12 小时前
【力扣热题100学习笔记】 - 哈希
java·学习·leetcode·哈希算法
凌波粒12 小时前
LeetCode--349.两个数组的交集(哈希表)
java·算法·leetcode·散列表
于先生吖13 小时前
Java+SpringBoot 无人健身房物联网系统完整源码实现
java·spring boot·物联网
johnrui13 小时前
SpringBoot-JdbcTemplate
java·spring boot·后端
码云社区13 小时前
JAVA二手车交易二手车市场系统源码支持微信小程序+微信公众号+H5+APP
java·开发语言·微信小程序·二手交易·闲置回收
crescent_悦13 小时前
C++:The Largest Generation
java·开发语言·c++
indexsunny13 小时前
互联网大厂Java面试实战:从Spring Boot到微服务的技术问答解析
java·spring boot·redis·微服务·消息队列·电商
希望永不加班14 小时前
SpringBoot 过滤器(Filter)与请求链路梳理
java·spring boot·后端·spring
Lyyaoo.14 小时前
【JAVA基础面经】抽象类/方法与接口
java·开发语言