Spring 设计模式之适配器模式

Spring 设计模式之适配器模式

适配器模式

适配器模式(Adapter Pattern)是一种结构型设计模式,它允许接口不兼容的类一起工作。

其核心思想是通过一个适配器类将不兼容的接口转换成客户端期望的另一个接口,使原本由于接口不兼容而不能一起工作的那些类可以一起工作

两者通过适配器一起工作,强调

1.通过实现目标接口和内部组合

2.实现的目标接口一定是旧对象

3.不是通过继承

用到的场景

1.新的对象,需要旧对象里面的方法

2.A有,B没有,B就通过适配器去获取A里面的元素(方法)

需要存在的核心类:

1.适配器类(实现旧对象)

java举例

java 复制代码
// 旧的打印机接口  
public interface OldPrinter {  
    void printOldWay(String content);  
}

// 旧的打印机实现  
public class OldPrinterImpl implements OldPrinter {  
    @Override  
    public void printOldWay(String content) {  
        System.out.println("使用旧的方式打印内容: " + content);  
    }  
}

// 新的打印机接口  
public interface NewPrinter {  
    void printNewWay(String content);  
}

// 适配器类,将旧的打印机适配为新的打印机  
public class PrinterAdapter implements NewPrinter {  
    private OldPrinter oldPrinter;  
  
    public PrinterAdapter(OldPrinter oldPrinter) {  
        this.oldPrinter = oldPrinter;  
    }  
  
    @Override  
    public void printNewWay(String content) {  
        // 适配过程:将新方式的内容适配为旧方式的内容进行打印  
        oldPrinter.printOldWay(content);  
    }  
}

// 新的文档类,它需要一个新打印机来打印  
public class NewDocument {  
    public void print(NewPrinter printer) {  
        printer.printNewWay("这是一个新文档的内容");  
    }  
}

// 调用使用示例
public class AdapterPatternDemo {  
    public static void main(String[] args) {  
        // 创建一个旧的打印机实例  
        OldPrinter oldPrinter = new OldPrinterImpl();  
  
        // 使用适配器将旧的打印机适配为新的打印机  
        NewPrinter newPrinter = new PrinterAdapter(oldPrinter);  
  
        // 创建一个新的文档并打印  
        NewDocument document = new NewDocument();  
        document.print(newPrinter);  
    }  
}

运行结果

java 复制代码
使用旧的方式打印内容: 这是一个新文档的内容
相关推荐
开longlong了吗?1 小时前
Luan Takeaway——大模型驱动的智能外卖管理系统( Spring Cloud、Langchain4j )
后端·spring·spring cloud·langchain
xu_ws3 小时前
Spring-ai项目-deepseek-6-哄哄模拟器
java·人工智能·spring
刘 大 望3 小时前
SpringAI Tool Calling(工具调用)
java·spring boot·spring·ai·maven·intellij-idea·文心一言
Je1lyfish6 小时前
CMU15-445 (2026 Spring) Project#2 - B+ Tree
linux·数据结构·数据库·c++·sql·spring·oracle
生产队队长6 小时前
SpringBoot3:ApplicationAvailability监控应用程序可用性状态[官方文档]
java·spring·mybatis
leikooo7 小时前
在 Spring AI 中自定义 Tool 调用返回值——实现 TodoList 提醒注入
spring
码喽7号7 小时前
Springboot学习五:MybatisPlus的快速上手
spring boot·学习·spring
weixin_704266058 小时前
事务管理全解析:从ACID到Spring实现
java·数据库·spring
逆境不可逃8 小时前
【从零入门23种设计模式18】行为型之备忘录模式
服务器·数据库·设计模式·oracle·职场和发展·迭代器模式·备忘录模式
Real-Staok9 小时前
(集合)C / C++ 设计模式综合
单例模式·设计模式·代理模式