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

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

代码示例:

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("你好适配器!"); 
    }
}

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

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

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

相关推荐
JH30731 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
m0_736919102 小时前
C++代码风格检查工具
开发语言·c++·算法
Coder_Boy_2 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
2501_944934732 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
invicinble2 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟3 小时前
使用ASM和agent监控属性变化
java
黎雁·泠崖3 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472463 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
TechWJ4 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
qq_12498707534 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计