适配器模式

所谓适配器模式就是将一个类的接口,转换成客户期望的另一个接口。它可以让原本两个不兼容的接口能够无缝完成对接。

让我们通过一个简单的例子来说明适配器模式。假设你有一个旧的系统,它有一个用于显示文本的组件,接口如下:

java 复制代码
// 旧的文本显示接口
interface OldTextComponent {
    void displayText(String text);
}

现在,你正在开发一个新的系统,它有一个名为 NewTextComponent 的文本显示组件,接口如下:

java 复制代码
// 新的文本显示接口
interface NewTextComponent {
    void show(String content);
}

但是,你的新系统中的某些部分需要使用旧系统的文本显示组件。这时候,适配器模式就可以派上用场。首先,创建一个适配器,将 OldTextComponent 适配成 NewTextComponent

java 复制代码
// 适配器类
class TextComponentAdapter implements NewTextComponent {
    private OldTextComponent oldTextComponent;

    public TextComponentAdapter(OldTextComponent oldTextComponent) {
        this.oldTextComponent = oldTextComponent;
    }

    @Override
    public void show(String content) {
        // 调用旧系统的方法来适配新系统的接口
        oldTextComponent.displayText(content);
    }
}

现在,你可以在新系统中使用适配器,无需修改旧系统的代码:

java 复制代码
public class Client {
    public static void main(String[] args) {
        // 使用新的文本组件
        NewTextComponent newTextComponent = new NewTextComponentImpl();
        newTextComponent.show("New System Text");

        // 使用适配器,将旧的文本组件适配成新的接口
        OldTextComponent oldTextComponent = new OldTextComponentImpl();
        NewTextComponent adapter = new TextComponentAdapter(oldTextComponent);
        adapter.show("Adapted Text");
    }
}

这样,通过适配器模式,你在新系统中可以无缝使用旧系统的组件,同时保持了新系统的一致性和灵活性。适配器将旧系统的接口转换成了新系统所需的接口,实现了两者的兼容。

相关推荐
明洞日记10 天前
【设计模式手册008】适配器模式 - 让不兼容的接口协同工作
java·设计模式·适配器模式
老鼠只爱大米13 天前
Java 设计模式之适配器模式:系统集成的万能接口
java·设计模式·适配器模式·adapter·java设计模式
小毛驴85014 天前
软件设计模式-适配器模式
电脑·适配器模式
朝新_15 天前
【统一功能处理】从入门到源码:拦截器学习指南(含适配器模式深度解读)
数据库·后端·mybatis·适配器模式·javaee
ruleslol25 天前
java-接口适配器模式 & jsk8 接口默认实现
java·适配器模式
Yeniden1 个月前
【设计模式】适配器模式大白话讲解!
设计模式·适配器模式
紫荆鱼1 个月前
设计模式-适配器模式(Adapter)
c++·设计模式·适配器模式
czy87874751 个月前
用C语言实现适配器模式
c语言·适配器模式
杯莫停丶1 个月前
设计模式之:适配器模式
设计模式·适配器模式
WaWaJie_Ngen1 个月前
【设计模式】适配器模式(Adapter)
设计模式·适配器模式