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

类适配器实现(继承)

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

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(); // 通过适配器调用被适配者方法
    }
}
相关推荐
永不停歇的蜗牛1 分钟前
K8S之创建cm指令create和 apply的区别
java·容器·kubernetes
爱学习的小可爱卢7 分钟前
JavaEE进阶——SpringBoot统一功能处理全解析
java·spring boot·后端·java-ee
汤姆yu9 分钟前
基于springboot的二手物品交易系统的设计与实现
java·spring boot·后端
中国胖子风清扬19 分钟前
Spring AI Alibaba + Ollama 实战:基于本地 Qwen3 的 Spring Boot 大模型应用
java·人工智能·spring boot·后端·spring·spring cloud·ai
alibli23 分钟前
一文学会设计模式之结构型模式及最佳实现
c++·设计模式
foundbug99936 分钟前
Modbus协议C语言实现(易于移植版本)
java·c语言·前端
听风吟丶39 分钟前
Java 反射机制深度解析:从原理到实战应用与性能优化
java·开发语言·性能优化
一缕猫毛40 分钟前
Flink demo代码
java·大数据·flink
小安同学iter1 小时前
天机学堂-优惠券功能-day09(七)
java·spring cloud·微服务·jenkins·优惠券·天机学堂
it_czz1 小时前
MCP调用流程图
java