简谈设计模式之适配器模式

适配器模式是结构型设计模式之一, 用于将一个类的接口转换成客户期望的另一个接口. 通过使用适配器模式, 原本由于接口不兼容而无法一起工作的类可以协同工作

适配器模式通常有两种实现方式

  1. 类适配器模式 (Class Adapter Pattern): 使用继承来实现适配器。
  2. **对象适配器模式 (Object Adapter Pattern) **: 使用组合来实现适配器。

适配器模式结构

  • 目标接口: 当前系统业务所期待的接口, 可以是抽象类也可以是接口
  • 适配者类: 它是被访问和适配的现存组件库中的组件接口
  • 适配器类: 它是一个转换器, 通过继承或引用适配者的对象, 把适配者接口转换成目标接口, 让客户按目标接口的格式访问适配者

适配器模式实现

  1. 类适配器模式

类适配器模式通过继承目标接口和被适配类, 实现适配功能

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

// 被适配者类
class Adaptee {
    void specificRequest() {
        System.out.println("Adaptee's specific request");
    }
}

// 类适配器
class ClassAdapter extends Adaptee implements Target {
    public void request() {
        specificRequest();
    }
}

// 客户端代码
public class Client {
    public static void main(String[] args) {
        Target target = new ClassAdapter();
        target.request();
    }
}
  1. 对象适配器模式

对象适配器模式通过组合的方式, 将被适配者类的实例作为适配器的一个字段, 并在适配器中调用被适配者的方法

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

// 被适配类
class Adaptee {
    void specificRequest() {
        System.out.println("Adaptee's specific request");
    }
}

// 对象适配器
class ObjectAdapter implements Target {
    private Adaptee adaptee;
    
    public ObjectAdapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }
    
    public void request() {
        adaptee.specificRequest();
    }
}

public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new ObjectAdapter();
        target.request();
    }
}

优点:

  1. 分离接口和实现: 适配器模式将客户端和被适配者类的接口分离开, 通过适配器类进行转换, 增强了代码的灵活性和可维护性
  2. 复用现有类: 通过适配器模式, 可以复用现有的类, 而不需要修改其代码, 从而满足新的需求

缺点

  1. 复杂性增加: 使用适配器模式会增加系统的复杂性, 尤其是需要同时适配多个类时, 可能需要大量的适配器类
  2. 性能开销: 适配器模式会引入额外的接口调用开销, 可能会对性能产生一定的影响
相关推荐
南山十一少3 小时前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
427724004 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo5 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦5 小时前
常用的 JVM 参数:配置与优化指南
java·jvm
计算机小白一个5 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
黑不溜秋的5 小时前
C++ 设计模式 - 策略模式
c++·设计模式·策略模式
付聪12107 小时前
策略模式介绍和代码示例
设计模式
南宫生8 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
计算机毕设定制辅导-无忧学长8 小时前
Maven 基础环境搭建与配置(一)
java·maven
ThereIsNoCode9 小时前
「软件设计模式」状态模式(State)
设计模式·状态模式