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

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

代码示例:

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

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

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

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

相关推荐
合作小小程序员小小店20 小时前
游戏开发,桌面%小游戏,贪吃蛇%demo,基于vs2022,c语言,easyX,无数据库
c语言·开发语言
天殇凉20 小时前
AC自动机学习笔记
java·笔记·学习
x***J34821 小时前
Python多线程爬虫
开发语言·爬虫·python
TechTrek21 小时前
Spring Boot 4.0正式发布了
java·spring boot·后端·spring boot 4.0
m***D28621 小时前
Python网络爬虫实战案例
开发语言·爬虫·python
保持低旋律节奏21 小时前
C++——C++11特性
开发语言·c++·windows
飞梦工作室21 小时前
企业级 Spring Boot 邮件系统开发指南:从基础到高可用架构设计
java·spring boot·后端
haiyu柠檬21 小时前
在Spring Boot中实现Azure的SSO+VUE3前端配置
java·spring boot·后端
ID_1800790547321 小时前
基于 Python 的淘宝商品详情数据结构化解析:SKU、价格与库存字段提取
开发语言·数据结构·python
星释21 小时前
Rust 练习册 82:Hamming与字符串处理
开发语言·算法·rust