【Java】23种设计模式——6.适配器模式

概念

适配器模式 : 转换接口兼容性,使得不兼容类可以协调工作。类似于现实重的适配器(将220V交流电,转换为5V的直流电)

适配模式的核心角色

  • 目标接口(Target) 客户端期望调用的接口
  • 被适配者(Adaptee) 需要被适配的现有类或接口
  • 适配器(Adapter) 实现目标接口,并包装被适配者的实例,负责接口转换。

适配器实现方式

类型 实现方式 适用场景
类适配器 ‌❎ 适配器继承被适配者类,并实现目标接口(需多继承支持) 适用于适配者与被适配者之间存在继承关系
对象适配器‌ ✅ 适配器持有被适配者对象,并实现目标接口(推荐方式) Java等单继承语言中的通用实现

适用场景

  • 整合遗留系统 : 将旧代码适配到新接口中。
  • 兼容第三方库: 统一不同组件的接口调用方式。
  • 接口版本升级 : 过渡期间保持新旧接共存。

步骤实现

1‌. 定义目标接口(Target)

// 目标接口:客户端期望的5V直流电接口
public interface DC5V {
    int output5V();
}

2‌. 实现被适配者(Adaptee)

// 被适配者:现有的220V交流电源
public class AC220V {
    public int output220V() {
        System.out.println("输出220V交流电");
        return 220;
    }
}

3‌. 创建适配器类(Adapter)

// 适配器:将220V交流电转换为5V直流电
public class PowerAdapter implements DC5V {
    private AC220V ac220V; // 持有被适配者对象

    public PowerAdapter(AC220V ac220V) {
        this.ac220V = ac220V;
    }

    @Override
    public int output5V() {
        int input = ac220V.output220V();
        int output = input / 44; // 模拟电压转换(220V→5V)
        System.out.println("适配器将电压转换为:" + output + "V");
        return output;
    }
}

4‌. 客户端调用

javpublic class Client {
    public static void main(String[] args) {
        // 创建被适配者对象
        AC220V ac220V = new AC220V();

        // 创建适配器并连接被适配者
        DC5V powerAdapter = new PowerAdapter(ac220V);

        // 客户端通过目标接口使用适配后的功能
        int output = powerAdapter.output5V();
        System.out.println("最终输出电压:" + output + "V");
    }
}

输出结果‌:

输出220V交流电
适配器将电压转换为:5V
最终输出电压:5V
posted @ 2025-06-20 15:25  陆陆无为而治者  阅读(41)  评论(0)    收藏  举报