关于java:聊一聊适配器模式

6次阅读

共计 7903 个字符,预计需要花费 20 分钟才能阅读完成。

接口不能用?行,我帮你适配

一、概述

适配器模式(Adapter),是 23 种设计模式中的 结构型模式 之一;它就像咱们电脑上接口不够时,须要用到的拓展坞,起到转接的作用。它能够将新的性能和原先的性能连接起来,使因为需要变动导致不能用的性能,从新利用起来。

上图的 Mac 上,只有两个 typec 接口,当咱们须要用到 USB、网线、HDMI 等接口时,这就不够用了,所以咱们须要一个拓展坞来减少电脑的接口

言归正传,上面来理解下适配器模式中的角色:请求者(client)、指标角色(Target)、源角色(Adaptee)、适配器角色(Adapter),这四个角色是保障这个设计模式运行的要害。

  • client:须要应用适配器的对象,不须要关怀适配器外部的实现,只对接指标角色。
  • Target:指标角色,和 client 间接对接,定义了 client 须要用到的性能。
  • Adaptee:须要被进行适配的对象。
  • Adapter:适配器,负责将源对象转化,给 client 做适配。

二、入门案例

适配器模式也分两种:对象适配器、类适配器。其实两种形式的区别在于,适配器类中的实现,类适配器是通过继承源对象的类,对象适配器是援用源对象的类。

当然两种形式各有优缺点,咱别离来说下;

类适配器:因为采纳继承模式,在适配器中能够重写 Adaptee 原有的办法,使得适配器能够更加灵便;然而有局限性,Java 是单继承模式,所以适配器类只能继承 Adaptee,不能在额定继承其余类,也导致 Target 类只能是接口。

对象适配器:这个模式躲避了单继承的劣势,将 Adaptee 类用援用的形式传递给 Adapter,这样能够传递的是 Adaptee 对象自身及其子类对象,相比类适配器更加的凋谢;然而也正是因为这种开放性,导致须要本人从新定义 Adaptee,减少额定的操作。

类适配器 UML 图

对象适配器 UML 图

上面,是联合下面电脑的场景,写的一个入门案例,别离是四个类:ClientAdapteeAdapterTarget,代表了适配器模式中的四种角色。

/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/9 15:54
 * @description:源角色
 */
public class Adaptee {
    /**
     * 须要被适配的适配的性能
     * 以 Mac 笔记本的 typec 接口举例
     */
    public void typeC() {System.out.println("我只是一个 typeC 接口");
    }
}
/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/9 15:57
 * @description:指标接口
 */
public interface Target {

    /**
     * 定义一个转接性能的入口
     */
    void socket();}
/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/9 16:00
 * @description:适配器
 */
public class Adapter extends Adaptee implements Target {

    /**
     * 实现适配性能
     * 以 Mac 的拓展坞为例,拓展更多的接口:usb、typc、网线插口...
     */
    @Override
    public void socket() {typeC();
        System.out.println("新增 usb 插口。。。");
        System.out.println("新增网线插口。。。");
        System.out.println("新增 typec 插口。。。");
    }
}
/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/9 15:52
 * @description:请求者
 */
public class Client {public static void main(String[] args) {Target target = new Adapter();
        target.socket();}
}

这个案例比较简单,仅仅是一个入门的 demo,也是类适配器模式的案例,采纳继承模式。在对象适配器模式中,区别就是 Adapter 这个适配器类,采纳的是组合模式,上面是对象适配器模式中 Adapter 的代码;

/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/9 16:00
 * @description:适配器
 */
public class Adapter implements Target {

    private Adaptee adaptee;

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

    /**
     * 实现适配性能
     * 以 Mac 的拓展坞为例,拓展更多的接口:usb、typc、网线插口...
     */
    @Override
    public void socket() {adaptee.typeC();
        System.out.println("新增 usb 插口。。。");
        System.out.println("新增网线插口。。。");
        System.out.println("新增 typec 插口。。。");
    }
}

三、使用场景

其实适配器模式为何会存在,全靠“烂代码”的烘托。在初期的设计上,一代目没有思考到前期的兼容性问题,只顾本人一时爽,那前期接手的人就会感觉到头疼,就会有“还不如重写这段代码的想法”。然而这部分代码往往都是通过 N 代人的充沛测试,稳定性比拟高,一时半会还不能对它下手。这时候咱们的适配器模式就孕育而生,能够在不动用老代码的前提下,实现新逻辑,并且能做二次封装。这种场景,我在之前的零碎重构中深有体会,不说了,都是泪。

当然还存在一种状况,能够对不同的内部数据进行对立输入。例如,写一个获取一些信息的接口,你对前端裸露的都是对立的返回字段,然而须要调用不同的内部 api 获取不同的信息,不同的 api 返回给你的字段都是不同的,比方企业工商信息、用户账户信息、用户津贴信息等等。上面我对这种场景具体分析下;

首先,我定义一个接口,接管用户 id 和数据类型两个参数,定义对立的输入字段。

/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/10 11:03
 * @description
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserInfoController {

    private final UserInfoTargetService userInfoTargetService;

    @PostMapping("/info")
    public Result<DataInfoVo> queryInfo(@RequestParam Integer userId, @RequestParam String type) {return Result.success(userInfoTargetService.queryData(userId, type));
    }
}

定义对立的输入的类DataInfoVo,这里定义的字段须要裸露给前端,具体业务意义跟前端约定。

/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/10 14:40
 * @description
 */
@Data
public class DataInfoVo {
    /**
     * 名称
     */
    private String name;
    /**
     * 类型
     */
    private String type;
    /**
     * 预留字段:具体业务意义自行定义
     */
    private Object extInfo;
}

而后,定义 Target 接口(篇幅起因,这里不做展现),Adapter 适配器类,这里采纳的是对象适配器,因为单继承的限度,对象适配器也是最罕用的适配器模式。

/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/10 15:09
 * @description
 */
@Service
@RequiredArgsConstructor
public class UserInfoAdapter implements UserInfoTargetService {
    /**
     * 源数据类管理器
     */
    private final AdapteeManager adapteeManager;

    @Override
    public DataInfoVo queryData(Integer userId, String type) {
        // 依据类型,失去惟一的源数据类
        UserBaseAdaptee adaptee = adapteeManager.getAdaptee(type);
        if (Objects.nonNull(adaptee)) {Object data = adaptee.getData(userId, type);
            return adaptee.convert(data);
        }
        return null;
    }
}

这里定义了一个 AdapteeManager 类,示意治理 Adaptee 类,外部保护一个 map,用于存储实在 Adaptee 类。

/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/10 15:37
 * @description
 */
public class AdapteeManager {

    private Map<String, UserBaseAdaptee> baseAdapteeMap;

    public void setBaseAdapteeMap(List<UserBaseAdaptee> adaptees) {baseAdapteeMap = adaptees.stream()
                .collect(Collectors.toMap(handler -> AnnotationUtils.findAnnotation(handler.getClass(), Adapter.class).type(), v -> v, (v1, v2) -> v1));
    }

    public UserBaseAdaptee getAdaptee(String type) {return baseAdapteeMap.get(type);
    }
}

最初,依照数据类型,定义了三个 Adaptee 类:AllowanceServiceAdaptee(津贴)、BusinessServiceAdaptee(企业工商)、UserAccountServiceAdaptee(用户账户)。

/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/10 15:00
 * @description
 */
@Adapter(type = "JT")
public class AllowanceServiceAdaptee implements UserBaseAdaptee {

    @Override
    public Object getData(Integer userId, String type) {
        // 模仿调用内部 api,查问津贴信息
        AllowanceVo allowanceVo = new AllowanceVo();
        allowanceVo.setAllowanceType("治理津贴");
        allowanceVo.setAllowanceAccount("xwqeretry2345676");
        allowanceVo.setAmount(new BigDecimal(20000));
        return allowanceVo;
    }

    @Override
    public DataInfoVo convert(Object data) {AllowanceVo preConvert = (AllowanceVo) data;
        DataInfoVo dataInfoVo = new DataInfoVo();
        dataInfoVo.setName(preConvert.getAllowanceAccount());
        dataInfoVo.setType(preConvert.getAllowanceType());
        dataInfoVo.setExtInfo(preConvert.getAmount());
        return dataInfoVo;
    }
}
/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/10 15:00
 * @description
 */
@Adapter(type = "QY")
public class BusinessServiceAdaptee implements UserBaseAdaptee {

    @Override
    public Object getData(Integer userId, String type) {
        // 模仿调用内部 api,查问企业工商信息
        BusinessVo businessVo = new BusinessVo();
        businessVo.setBusName("xxx 科技有限公司");
        businessVo.setBusCode("q24243Je54sdfd99");
        businessVo.setBusType("中大型企业");
        return businessVo;
    }

    @Override
    public DataInfoVo convert(Object data) {BusinessVo preConvert = (BusinessVo) data;
        DataInfoVo dataInfoVo = new DataInfoVo();
        dataInfoVo.setName(preConvert.getBusName());
        dataInfoVo.setType(preConvert.getBusType());
        dataInfoVo.setExtInfo(preConvert.getBusCode());
        return dataInfoVo;
    }
}
/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/10 15:00
 * @description
 */
@Adapter(type = "YH")
public class UserAccountServiceAdaptee implements UserBaseAdaptee {

    @Override
    public Object getData(Integer userId, String type) {
        // 模仿调用内部 api,查问企业工商信息
        UserAccountVo userAccountVo = new UserAccountVo();
        userAccountVo.setAccountNo("afsdfd1243567");
        userAccountVo.setAccountType("银行卡");
        userAccountVo.setName("中国农业银行");
        return userAccountVo;
    }

    @Override
    public DataInfoVo convert(Object data) {UserAccountVo preConvert = (UserAccountVo) data;
        DataInfoVo dataInfoVo = new DataInfoVo();
        dataInfoVo.setName(preConvert.getName());
        dataInfoVo.setType(preConvert.getAccountType());
        dataInfoVo.setExtInfo(preConvert.getAccountNo());
        return dataInfoVo;
    }
}

这三个类都实现一个接口UserBaseAdaptee,该接口定义了对立的标准

/**
 * @author 往事如风
 * @version 1.0
 * @date 2023/5/10 15:03
 * @description
 */

public interface UserBaseAdaptee {
    /**
     * 获取数据
     * @param userId
     * @param type
     * @return
     */
    Object getData(Integer userId, String type);

    /**
     * 数据转化为对立的实体
     * @param data
     * @return
     */
    DataInfoVo convert(Object data);
}

这些类中,其实重点看下 UserInfoAdapter 适配器类,这里做的操作是通过源数据类,拿到内部返回的数据,最初将不同的数据转化为对立的字段,返回进来。

这里我没有依照固定的模式,稍加了扭转。将适配器类中援用源数据类的形式,改成将源数据类退出 map 中暂存,最初通过前端传输的 type 字段来获取源数据类,这也是对象适配器比拟灵便的一种体现。

四、源码中的使用

在 JDK 的源码中,JUC 下有个类FutureTask,其中它的一段构造方法如下:

public class FutureTask<V> implements RunnableFuture<V> {public FutureTask(Callable<V> callable) {if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
    
    public FutureTask(Runnable runnable, V result) {this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }
}

其中一个构造函数中,callable 是通过 Executors 类的办法进行适配的,通过一个 RunnableAdapter 的适配器类,进行包装并返回

public static <T> Callable<T> callable(Runnable task, T result) {if (task == null)
            throw new NullPointerException();
        return new RunnableAdapter<T>(task, result);
    }
static final class RunnableAdapter<T> implements Callable<T> {
        final Runnable task;
        final T result;
        RunnableAdapter(Runnable task, T result) {
            this.task = task;
            this.result = result;
        }
        public T call() {task.run();
            return result;
        }
    }

这样的话,无论传入 Runnable 还是 Callable 都能够适配工作,尽管看着是调用了 Callable 的 call 办法,理论外部是调用了 Runnable 的 run 办法,并且将传入的返回数据返回给内部应用。

五、总结

适配器模式其实是一个比拟好了解的设计模式,然而对于大多数初学者而言,就会很容易看一遍之后立马忘,这是短少理论使用造成的。其实编程次要考查的还是咱们的一种思维模式,就像这个适配器模式,了解它的使用场景最重要。如果给你一个业务场景,你能在脑海中有大抵的设计思路或者解决方案,那你就曾经把握精华了。至于具体的落地,有些细节遗记也是在劫难逃,翻翻材料就会立马回到脑海中。

最初,每次遇到问题,用心总结,你会离胜利更近一步。

六、参考源码

编程文档:https://gitee.com/cicadasmile/butte-java-note

利用仓库:https://gitee.com/cicadasmile/butte-flyer-parent
正文完
 0