适配器模式:兼容不兼容接口

将一个类的接口转换成客户端期望的另一个接口,解决接口不兼容问题。

代码示例:

java 复制代码
// 目标接口(客户端期望的格式)
interface ModernPrinter {
    void printDocument(String text);
}

// 被适配的旧类(不兼容)
class LegacyPrinter {
    void print(String message, int copies) {
        for (int i = 0; i < copies; i++) {
            System.out.println("旧类打印: " + message);
        }
    }
}

// 适配器类(转换接口)
class PrinterAdapter implements ModernPrinter {
    private final LegacyPrinter legacyPrinter = new LegacyPrinter();
    
    @Override
    public void printDocument(String text) {
        // 调用旧类方法并适配参数
        legacyPrinter.print(text, 1); // 默认打印1份
    }
}

// 客户端调用
public class Client {
    public static void main(String[] args) {
        ModernPrinter printer = new PrinterAdapter();
        printer.printDocument("你好适配器!"); 
    }
}

**使用场景:**整合第三方库/遗留代码、系统接口升级时兼容旧模块

**优点:**复用现有代码;灵活性高

**缺点:**过度使用会导致系统结构混乱

相关推荐
Highcharts.js29 分钟前
Highcharts漏斗图表使用配置指南
java·开发语言·javascript·信息可视化·highcharts·漏斗图
武昌库里写JAVA5 小时前
SpringBoot+Vue 项目介绍
java·javascript·git·sql·ai
学长毕设6 小时前
基于SpringBoot的儿童慈善捐赠管理系统-附源码
java·spring boot·后端
慧一居士6 小时前
@RestControllerAdvice 的注解作用和使用
java
ComPDFKit6 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
FRing037 小时前
vue3干货总结2(vue3生命周期、父子通信、模版引用、provide和inject)
开发语言·前端·vue.js·vue3
学长毕设7 小时前
基于SpringBoot非遗文化展示与传播平台设计与实现-附源码
java·spring boot·后端
金銀銅鐵9 小时前
用 Swing 重做操作数栈演示
java·jvm·后端
琳少_9 小时前
java程序开发笔记
java·开发语言·数据库·笔记
七夜zippoe9 小时前
Agent 告警设计:分级告警、智能降噪与值班排班
开发语言·ai·agent·告警·智能降噪·值班排班