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

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

代码示例:

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

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

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

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

相关推荐
ps酷教程5 小时前
Jackson 解决没有无参构造函数的反序列化问题
java
NiceCloud喜云6 小时前
Opus 4.8 的 Effort Control 怎么选:Low 到 Max 五档策略
android·java·大数据·前端·c++·python·spring
AI玫瑰助手6 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车6 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋6 小时前
C++14特性
开发语言·c++·c++14特性
_日拱一卒6 小时前
LeetCode:994腐烂的橘子
java·数据结构·算法·leetcode·深度优先
隔窗听雨眠7 小时前
Nginx网关响应慢排查手记
java·服务器·nginx
智慧物业老杨7 小时前
智慧物业合同周期管理系统:从风险预警到智能交接的全流程数智化落地方案
java·人工智能·python
源码宝7 小时前
MES系统源码:Java8 + SpringBoot2.7 + MySQL8 + Redis,后端源码清爽易扩展
java·后端·源码·springboot·mes系统·源码二开·mes源码
JAVA社区8 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展