设计模式之【适配器模式】

类适配器实现(继承)

类适配器通过继承来实现适配器功能

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

// 被适配者
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

// 适配器
public class Adapter extends Adaptee implements Target {
    /**
     * 采用继承的方式实现转换功能
     */
    @Override
    public void request() {
        super.specificRequest();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者方法
    }
}

对象适配器实现(组合)

对象适配器通过组合来实现适配器功能

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

// 被适配者
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee: specificRequest");
    }
}

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

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

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

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者方法
    }
}
相关推荐
OH_TPC2 小时前
HarmonyOS APP开发---“滤镜大师“图像处理App,需要用到这个库
java·图像处理·华为·harmonyos·鸿蒙
imaol14 小时前
链表 -- 环链表
java·前端·链表
imaol14 小时前
链表 -- 双向链表
java·前端·链表
2601_963869954 小时前
【计算机毕业设计】基于Java的相框定制系统的设计与实现
java·开发语言·课程设计
George_Ye5 小时前
同一本书,一人一份:我如何设计 AI 个性化扫书报告
设计模式
于烛5 小时前
为什么hasNext() 对只有一个元素的集合返回 true?90%初学者都有的疑问
java
wuminyu5 小时前
JVM利用io_uring优化堆外内存性能原理剖析
java·linux·c语言·jvm·c++
imaol16 小时前
数据结构---队列
java·数据结构·算法
半亩码田6 小时前
【.NET新特性·第11篇】C# 14 字段属性:告别手写 backing field
java·c#·.net
JAVA面经实录9177 小时前
集合框架 (六)
java·开发语言