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

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

代码示例:

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

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

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

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

相关推荐
xingshanchang5 分钟前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc6 分钟前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
AI视觉网奇12 分钟前
git 访问 github
运维·开发语言·docker
不知道叫什么呀19 分钟前
【C】vector和array的区别
java·c语言·开发语言·aigc
liulilittle39 分钟前
.NET ExpandoObject 技术原理解析
开发语言·网络·windows·c#·.net·net·动态编程
wan_da_ren1 小时前
JVM监控及诊断工具-GUI篇
java·开发语言·jvm·后端
委婉待续1 小时前
计算机网络通信的相关知识总结
开发语言·网络
cui_hao_nan1 小时前
JAVA并发——什么是Java的原子性、可见性和有序性
java·开发语言
best_virtuoso1 小时前
JAVA JVM垃圾收集
java·开发语言·jvm
lifallen1 小时前
Kafka 时间轮深度解析:如何O(1)处理定时任务
java·数据结构·分布式·后端·算法·kafka