设计模式-适配器模式

适配器模式是一种结构型设计模式,用于将一个类的接口转换成客户端所期望的另一个接口。这种模式可以解决由于接口不兼容而无法合作的问题。

在 Java 中,适配器模式可以通过以下步骤实现:

  1. 定义目标接口(Target Interface):这是客户端所期望的接口,也是适配器要实现的接口。

  2. 创建适配器类(Adapter Class):适配器类实现了目标接口,并持有一个对被适配对象的引用。

  3. 创建被适配类(Adaptee Class):被适配类是需要被适配的类,它拥有不兼容的接口。

  4. 在适配器类中实现目标接口的方法:适配器类中的方法将调用被适配类的方法来完成适配。

以下是一个简单的示例代码,演示了适配器模式的实现:

复制代码
// 目标接口
interface Target {
    void request();
}

// 被适配类
class Adaptee {
    void specificRequest() {
        System.out.println("Adaptee's specific request");
    }
}

// 适配器类
class Adapter implements Target {
    private Adaptee adaptee;

    Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

// 客户端代码
public class Main {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request();
    }
}

在上面的示例中,Target 是目标接口,Adaptee 是被适配类,Adapter 是适配器类。适配器类实现了目标接口,并在其方法中调用了被适配类的方法。

当客户端调用适配器的 request() 方法时,实际上是通过适配器间接调用了被适配类的 specificRequest() 方法,从而实现了适配。

相关推荐
咖啡八杯1 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
槑有老呆3 天前
别再手搓 Prompt 了,那个叫"手动挡循环"
设计模式
用户6919026813393 天前
Vibe Coding 开发项目的基本范式
人工智能·设计模式·代码规范
怕浪猫4 天前
领域特定语言(Domain-Specific Language, DSL)
设计模式·程序员·架构
Larcher6 天前
AI Loop:让AI像人一样自主完成任务的核心机制
javascript·人工智能·设计模式
咖啡八杯7 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
:mnong7 天前
学习创建结构行为设计模式
设计模式
w_t_y_y8 天前
Agent设计模式(四)多模态融合模式(Multi-Modal Fusion)
设计模式