设计模式-适配器模式

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

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

相关推荐
庞轩px19 小时前
HotSpot详解——符号引用、句柄池、直接指针的终极解密
java·jvm·设计模式·内存·虚拟机·引用·klass
Yu_Lijing21 小时前
基于C++的《Head First设计模式》笔记——责任链模式
c++·笔记·设计模式·责任链模式
青木川崎1 天前
设计模式之面试题
java·开发语言·设计模式
Yu_Lijing2 天前
基于C++的《Head First设计模式》笔记——生成器模式
c++·笔记·设计模式
sg_knight2 天前
设计模式实战:策略模式(Strategy)
java·开发语言·python·设计模式·重构·架构·策略模式
吐个泡泡v2 天前
Python 开发“设计模式”指南
python·设计模式
程序员小寒2 天前
JavaScript设计模式(一):单例模式实现与应用
javascript·单例模式·设计模式
砍光二叉树2 天前
【设计模式】创建型-原型模式
设计模式·原型模式
helloworddm2 天前
第一篇:设计模式在 Android 视频播放器中的实战应用
android·设计模式·音视频