设计模式-适配器模式

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

在 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() 方法,从而实现了适配。

相关推荐
Seven971 小时前
【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
java·后端·设计模式
康凯哇咔咔1 小时前
代理模式(Proxy Pattern)
设计模式·c#·代理模式
香菇滑稽之谈2 小时前
代理模式的C++实现示例
c++·设计模式·系统安全·代理模式
shinelord明2 小时前
【软件设计】23 种设计模式解析与实践指南
数据结构·设计模式·软件工程
LuckyLay11 小时前
Golang学习笔记_49——解释器模式
笔记·学习·设计模式·golang·解释器模式
NorthCastle13 小时前
设计模式-结构型模式-桥接模式
java·设计模式·桥接模式
新停浊酒杯15 小时前
设计模式——策略模式以及基于Spring依赖注入的策略模式的应用
设计模式·策略模式
小王子102415 小时前
设计模式Python版 策略模式
python·设计模式·策略模式
杨充15 小时前
06.依赖倒置原则介绍
设计模式
seven97_top18 小时前
【设计模式】掌握建造者模式:如何优雅地解决复杂对象创建难题?
java·设计模式·建造者模式