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 复制代码
使用旧的方式打印内容: 这是一个新文档的内容
相关推荐
纪莫6 小时前
技术面:SpringBoot(springboot的类加载和传统的双亲委派有什么区别、如何按顺序实例化Bean)
java·spring·java面试⑧股
曾经的三心草6 小时前
springcloud二-Seata3- Seata各事务模式
后端·spring·spring cloud
Elieal8 小时前
Spring 框架IOC和AOP
java·数据库·spring
喝茶与编码9 小时前
工厂模式+抽象类 实战指南(基于文档导出业务)
设计模式
Java水解9 小时前
Spring AI Alibaba 入门教程:快速集成大模型到Spring Boot应用
后端·spring
塔能物联运维10 小时前
物联网边缘节点数据缓存优化与一致性保障技术
java·后端·物联网·spring·缓存
初学者,亦行者10 小时前
Rayon并行迭代器:原理、实践与性能优化
java·开发语言·spring·rust
昨天的猫12 小时前
原来项目中的观察者模式是这样玩的
后端·设计模式
2301_7951672014 小时前
玩转Rust高级应用 如何进行面向对象设计模式的实现,实现状态模式
设计模式·rust·状态模式
星夜泊客1 天前
Unity 游戏开发中的防御性编程与空值处理实践
unity·设计模式·游戏引擎