设计模式-适配器模式

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

在 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 小时前
设计模式-创建型-常用:单例模式、工厂模式、建造者模式
单例模式·设计模式·建造者模式·工厂模式
严文文-Chris3 小时前
【设计模式-中介者模式】
设计模式·中介者模式
刷帅耍帅3 小时前
设计模式-中介者模式
设计模式·中介者模式
刷帅耍帅4 小时前
设计模式-组合模式
设计模式·组合模式
刷帅耍帅5 小时前
设计模式-命令模式
设计模式·命令模式
码龄3年 审核中5 小时前
设计模式、系统设计 record part03
设计模式
刷帅耍帅5 小时前
设计模式-外观模式
设计模式·外观模式
刷帅耍帅6 小时前
设计模式-迭代器模式
设计模式·迭代器模式
liu_chunhai6 小时前
设计模式(3)builder
java·开发语言·设计模式
刷帅耍帅6 小时前
设计模式-策略模式
设计模式·策略模式