聊一聊适配器模式

博客 动态
0 158
羽尘
羽尘 2023-05-17 08:55:10
悬赏:0 积分 收藏

聊一聊适配器模式

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

一、概述

适配器模式(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方法,并且将传入的返回数据返回给外部使用。

五、总结

适配器模式其实是一个比较好理解的设计模式,但是对于大多数初学者而言,就会很容易看一遍之后立马忘,这是缺少实际运用造成的。其实编程主要考察的还是我们的一种思维模式,就像这个适配器模式,理解它的运用场景最重要。如果给你一个业务场景,你能在脑海中有大致的设计思路或者解决方案,那你就已经掌握精髓了。至于具体的落地,有些细节忘记也是在所难免,翻翻资料就会立马回到脑海中。

最后,每次遇到问题,用心总结,你会离成功更近一步。

posted @ 2023-05-17 08:35  知了一笑  阅读(0)  评论(0编辑  收藏  举报
回帖
    羽尘

    羽尘 (王者 段位)

    2233 积分 (2)粉丝 (11)源码

     

    温馨提示

    亦奇源码

    最新会员