java设计模式之 - 适配器模式

想学习springboot,springboot+vue项目,SpringCloudAlibaba的小伙伴,可以免费观看视频地址:

html 复制代码
springcloudalibaba地址:
https://www.bilibili.com/video/BV1cFDEYWEkY/?vd_source=14d27ec13a4737c281b7c79463687112
html 复制代码
springboot地址:
https://www.bilibili.com/video/BV1nkmRYSErk/?vd_source=14d27ec13a4737c281b7c79463687112
html 复制代码
springboot+vue案例地址:
https://www.bilibili.com/video/BV1JLSEYJETc/?vd_source=14d27ec13a4737c281b7c79463687112

**适配器模式(Adapter Pattern)**是一种结构型设计模式,它允许不兼容的接口之间的协同工作,通常用于将一个类的接口转换成客户端期望的另一个接口。适配器让那些接口不兼容的类可以一起工作。

适配器模式的主要角色:

  1. 目标接口(Target):客户期望的接口。
  2. 适配者(Adaptee):需要被适配的类。
  3. 适配器(Adapter):将适配者接口转换为目标接口的类。

简单案例:

假设我们有一个 Adaptee 类,它有一个 specificRequest() 方法,但是客户期望的接口是 Target 接口中的 request() 方法。我们的任务是创建一个 Adapter 类来使得 Adaptee 类能够以 Target 接口的形式被使用。

1. 定义目标接口(Target)
java 复制代码
public interface Target {
    void request();
}
2. 创建适配者类(Adaptee)
java 复制代码
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: Specific request executed.");
    }
}
3. 创建适配器类(Adapter)
java 复制代码
public class Adapter implements Target {
    private Adaptee adaptee;

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

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}
4. 客户端代码
java 复制代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 这将调用 Adaptee 的 specificRequest() 方法
    }
}

在这个案例中,Adapter 类实现了 Target 接口,并在内部持有 Adaptee 类的实例。Adapter 类的 request() 方法调用了 Adaptee 类的 specificRequest() 方法,从而使得 Adaptee 类能够以 Target 接口的形式被使用。

当你运行 Client 类的 main 方法时,你将看到以下输出:

复制代码
Adaptee: Specific request executed.

这表明适配器模式成功地将 Adaptee 类适配到了 Target 接口,使得客户端代码可以无缝地使用 Adaptee 类的功能。

相关推荐
代码小将1 小时前
Leetcode209做题笔记
java·笔记·算法
专注_每天进步一点点1 小时前
idea 启动Springboot项目在编译阶段报错:java: OutOfMemoryError: insufficient memory
java·spring boot·intellij-idea
dhxhsgrx2 小时前
PYTHON训练营DAY25
java·开发语言·python
君鼎3 小时前
C++设计模式——单例模式
c++·单例模式·设计模式
不知几秋3 小时前
数字取证-内存取证(volatility)
java·linux·前端
敲代码的 蜡笔小新5 小时前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
令狐前生5 小时前
设计模式学习整理
学习·设计模式
chxii6 小时前
5java集合框架
java·开发语言
敲代码的 蜡笔小新7 小时前
【行为型之解释器模式】游戏开发实战——Unity动态公式解析与脚本系统的架构奥秘
unity·设计模式·游戏引擎·解释器模式
yychen_java7 小时前
R-tree详解
java·算法·r-tree