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

类适配器实现(继承)

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

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(); // 通过适配器调用被适配者方法
    }
}
相关推荐
对许13 分钟前
Java操作Excel最佳实践
java·spark·excel
高级程序源20 分钟前
springboot学生档案信息管理系统-计算机毕业设计源码96509
java·spring boot·spring·eclipse·mybatis·idea
普通程序员A37 分钟前
代码技巧专题 -- 使用策略模式编写HandleService
设计模式·面试·策略模式·代码优化·handle
martian66543 分钟前
学懂C#编程:属性(Property)的概念定义及使用详解
java·开发语言·c#·属性·property
阿亮说技术1 小时前
Java毕业设计 基于SSM vue电影院票务系统小程序 微信小程序
java·微信小程序·毕业设计·课程设计
时间瑾1 小时前
线程池实践篇
java·开发语言
ffyyhh9955111 小时前
记一次kafka使用不当导致的服务器异常
java
不要飞升1 小时前
百日筑基第十一天-看看SpringBoot
java·spring boot·后端·实习
萝卜地里的兔子1 小时前
面向对象编程思想新解 第二章 编程的本质
java·开发语言
xw-pp1 小时前
回溯法的小结与概述
java·数据结构·c++·python·算法·递归