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 复制代码
使用旧的方式打印内容: 这是一个新文档的内容
相关推荐
麦兜*9 分钟前
Redis内存消耗异常飙升?深入排查与Big Key/Hot Key的根治方案
jvm·数据库·spring boot·redis·spring·缓存
小七mod1 小时前
【Spring】Spring Boot自动配置的案例
java·spring boot·spring·自动配置·源码·ioc·aop
java干货1 小时前
Spring Boot 为什么“抛弃”了 spring.factories?
spring boot·python·spring
在未来等你1 小时前
AI Agent设计模式 Day 7:Tree-of-Thoughts模式:树形思维探索
设计模式·llm·react·ai agent·plan-and-execute
sg_knight1 小时前
RabbitMQ 中的预取值(prefetch)详解:如何真正提升消费端性能?
java·spring boot·spring·spring cloud·消息队列·rabbitmq·预取值
烤麻辣烫2 小时前
23种设计模式(新手)-5里氏替换原则
java·学习·设计模式·intellij-idea·里氏替换原则
g***B7382 小时前
前端组件设计模式,复用与扩展
前端·设计模式
百***61873 小时前
Spring的构造注入
android·java·spring
桦说编程3 小时前
如果让我从头再来学习并发编程
java·设计模式·性能优化
明洞日记4 小时前
【设计模式手册006】建造者模式 - 复杂对象的优雅构建之道
java·设计模式·建造者模式