设计模式之【适配器模式】

类适配器实现(继承)

类适配器通过继承来实现适配器功能

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

// 被适配者
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

// 适配器
public class Adapter extends Adaptee implements Target {
    /**
     * 采用继承的方式实现转换功能
     */
    @Override
    public void request() {
        super.specificRequest();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者方法
    }
}

对象适配器实现(组合)

对象适配器通过组合来实现适配器功能

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

// 被适配者
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

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

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

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

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者方法
    }
}
相关推荐
皮皮林5514 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河4 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
桦说编程7 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅9 小时前
Java面向对象入门(类与对象,新手秒懂)
java
静水流深_沧海一粟9 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder9 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
初次攀爬者9 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺9 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart11 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot