代码越写越乱?那是因为你没用责任链

2023-10-27

路人 Java充电社 2022-08-04 08:06 发表于上海

收录于合集#java充电社244个

大家好,我是路人~~~

最近,我让团队内一位成员写了一个导入功能。他使用了责任链模式,代码堆的非常多,bug 也多,没有达到我预期的效果。

实际上,针对导入功能,我认为模版方法更合适!为此,隔壁团队也拿出我们的案例,进行了集体 code review。

学好设计模式,且不要为了练习,强行使用!让原本 100 行就能实现的功能,写了 3000 行!对错暂且不论,我们先一起看看责任链设计模式吧!

什么是责任链

责任链模式是一种行为设计模式, 允许你将请求沿着处理者链进行发送。收到请求后, 每个处理者均可对请求进行处理, 或将其传递给链上的下个处理者。

使用场景

责任链的使用场景还是比较多的:

  • 多条件流程判断:权限控制

  • ERP 系统流程审批:总经理、人事经理、项目经理

  • Java 过滤器的底层实现 Filter

如果不使用该设计模式,那么当需求有所改变时,就会使得代码臃肿或者难以维护,例如下面的例子。

| 反例

假设现在有一个闯关游戏,进入下一关的条件是上一关的分数要高于 xx:

  • 游戏一共 3 个关卡

  • 进入第二关需要第一关的游戏得分大于等于 80

  • 进入第三关需要第二关的游戏得分大于等于 90

那么代码可以这样写:

//第一关
public class FirstPassHandler {
    public int handler(){
        System.out.println("第一关-->FirstPassHandler");
        return 80;
    }
}

//第二关
public class SecondPassHandler {
    public int handler(){
        System.out.println("第二关-->SecondPassHandler");
        return 90;
    }
}


//第三关
public class ThirdPassHandler {
    public int handler(){
        System.out.println("第三关-->ThirdPassHandler,这是最后一关啦");
        return 95;
    }
}


//客户端
public class HandlerClient {
    public static void main(String[] args) {

        FirstPassHandler firstPassHandler = new FirstPassHandler();//第一关
        SecondPassHandler secondPassHandler = new SecondPassHandler();//第二关
        ThirdPassHandler thirdPassHandler = new ThirdPassHandler();//第三关

        int firstScore = firstPassHandler.handler();
        //第一关的分数大于等于80则进入第二关
        if(firstScore >= 80){
            int secondScore = secondPassHandler.handler();
            //第二关的分数大于等于90则进入第二关
            if(secondScore >= 90){
                thirdPassHandler.handler();
            }
        }
    }
}

那么如果这个游戏有 100 关,我们的代码很可能就会写成这个样子:

if(第1关通过){
    // 第2关 游戏
    if(第2关通过){
        // 第3关 游戏
        if(第3关通过){
           // 第4关 游戏
            if(第4关通过){
                // 第5关 游戏
                if(第5关通过){
                    // 第6关 游戏
                    if(第6关通过){
                        //...
                    }
                }
            } 
        }
    }
}

这种代码不仅冗余,并且当我们要将某两关进行调整时会对代码非常大的改动,这种操作的风险是很高的,因此,该写法非常糟糕。

| 初步改造

如何解决这个问题,我们可以通过链表将每一关连接起来,形成责任链的方式,第一关通过后是第二关,第二关通过后是第三关....

这样客户端就不需要进行多重 if 的判断了:

public class FirstPassHandler {
    /**
     * 第一关的下一关是 第二关
     */
    private SecondPassHandler secondPassHandler;

    public void setSecondPassHandler(SecondPassHandler secondPassHandler) {
        this.secondPassHandler = secondPassHandler;
    }

    //本关卡游戏得分
    private int play(){
        return 80;
    }

    public int handler(){
        System.out.println("第一关-->FirstPassHandler");
        if(play() >= 80){
            //分数>=80 并且存在下一关才进入下一关
            if(this.secondPassHandler != null){
                return this.secondPassHandler.handler();
            }
        }

        return 80;
    }
}

public class SecondPassHandler {

    /**
     * 第二关的下一关是 第三关
     */
    private ThirdPassHandler thirdPassHandler;

    public void setThirdPassHandler(ThirdPassHandler thirdPassHandler) {
        this.thirdPassHandler = thirdPassHandler;
    }

    //本关卡游戏得分
    private int play(){
        return 90;
    }

    public int handler(){
        System.out.println("第二关-->SecondPassHandler");

        if(play() >= 90){
            //分数>=90 并且存在下一关才进入下一关
            if(this.thirdPassHandler != null){
                return this.thirdPassHandler.handler();
            }
        }

        return 90;
    }
}

public class ThirdPassHandler {

    //本关卡游戏得分
    private int play(){
        return 95;
    }

    /**
     * 这是最后一关,因此没有下一关
     */
    public int handler(){
        System.out.println("第三关-->ThirdPassHandler,这是最后一关啦");
        return play();
    }
}

public class HandlerClient {
    public static void main(String[] args) {

        FirstPassHandler firstPassHandler = new FirstPassHandler();//第一关
        SecondPassHandler secondPassHandler = new SecondPassHandler();//第二关
        ThirdPassHandler thirdPassHandler = new ThirdPassHandler();//第三关

        firstPassHandler.setSecondPassHandler(secondPassHandler);//第一关的下一关是第二关
        secondPassHandler.setThirdPassHandler(thirdPassHandler);//第二关的下一关是第三关

        //说明:因为第三关是最后一关,因此没有下一关
        //开始调用第一关 每一个关卡是否进入下一关卡 在每个关卡中判断
        firstPassHandler.handler();

    }
}

| 缺点

现有模式的缺点:

  • 每个关卡中都有下一关的成员变量并且是不一样的,形成链很不方便

  • 代码的扩展性非常不好

| 责任链改造

既然每个关卡中都有下一关的成员变量并且是不一样的,那么我们可以在关卡上抽象出一个父类或者接口,然后每个具体的关卡去继承或者实现。

有了思路,我们先来简单介绍一下责任链设计模式的基本组成:

  • 抽象处理者(Handler)角色:定义一个处理请求的接口,包含抽象处理方法和一个后继连接。

  • 具体处理者(Concrete Handler)角色:实现抽象处理者的处理方法,判断能否处理本次请求,如果可以处理请求则处理,否则将该请求转给它的后继者。

  • 客户类(Client)角色:创建处理链,并向链头的具体处理者对象提交请求,它不关心处理细节和请求的传递过程。

public abstract class AbstractHandler {

    /**
     * 下一关用当前抽象类来接收
     */
    protected AbstractHandler next;

    public void setNext(AbstractHandler next) {
        this.next = next;
    }

    public abstract int handler();
}

public class FirstPassHandler extends AbstractHandler{

    private int play(){
        return 80;
    }

    @Override
    public int handler(){
        System.out.println("第一关-->FirstPassHandler");
        int score = play();
        if(score >= 80){
            //分数>=80 并且存在下一关才进入下一关
            if(this.next != null){
                return this.next.handler();
            }
        }
        return score;
    }
}

public class SecondPassHandler extends AbstractHandler{

    private int play(){
        return 90;
    }

    public int handler(){
        System.out.println("第二关-->SecondPassHandler");

        int score = play();
        if(score >= 90){
            //分数>=90 并且存在下一关才进入下一关
            if(this.next != null){
                return this.next.handler();
            }
        }

        return score;
    }
}

public class ThirdPassHandler extends AbstractHandler{

    private int play(){
        return 95;
    }

    public int handler(){
        System.out.println("第三关-->ThirdPassHandler");
        int score = play();
        if(score >= 95){
            //分数>=95 并且存在下一关才进入下一关
            if(this.next != null){
                return this.next.handler();
            }
        }
        return score;
    }
}

public class HandlerClient {
    public static void main(String[] args) {

        FirstPassHandler firstPassHandler = new FirstPassHandler();//第一关
        SecondPassHandler secondPassHandler = new SecondPassHandler();//第二关
        ThirdPassHandler thirdPassHandler = new ThirdPassHandler();//第三关

        // 和上面没有更改的客户端代码相比,只有这里的set方法发生变化,其他都是一样的
        firstPassHandler.setNext(secondPassHandler);//第一关的下一关是第二关
        secondPassHandler.setNext(thirdPassHandler);//第二关的下一关是第三关

        //说明:因为第三关是最后一关,因此没有下一关

        //从第一个关卡开始
        firstPassHandler.handler();

    }
}

 

| 责任链工厂改造

对于上面的请求链,我们也可以把这个关系维护到配置文件中或者一个枚举中。我将使用枚举来教会大家怎么动态的配置请求链并且将每个请求者形成一条调用链。

public enum GatewayEnum {
    // handlerId, 拦截者名称,全限定类名,preHandlerId,nextHandlerId
    API_HANDLER(new GatewayEntity(1, "api接口限流", "cn.dgut.design.chain_of_responsibility.GateWay.impl.ApiLimitGatewayHandler", null, 2)),
    BLACKLIST_HANDLER(new GatewayEntity(2, "黑名单拦截", "cn.dgut.design.chain_of_responsibility.GateWay.impl.BlacklistGatewayHandler", 1, 3)),
    SESSION_HANDLER(new GatewayEntity(3, "用户会话拦截", "cn.dgut.design.chain_of_responsibility.GateWay.impl.SessionGatewayHandler", 2, null)),
    ;

    GatewayEntity gatewayEntity;

    public GatewayEntity getGatewayEntity() {
        return gatewayEntity;
    }

    GatewayEnum(GatewayEntity gatewayEntity) {
        this.gatewayEntity = gatewayEntity;
    }
}

public class GatewayEntity {

    private String name;

    private String conference;

    private Integer handlerId;

    private Integer preHandlerId;

    private Integer nextHandlerId;
}


public interface GatewayDao {

    /**
     * 根据 handlerId 获取配置项
     * @param handlerId
     * @return
     */
    GatewayEntity getGatewayEntity(Integer handlerId);

    /**
     * 获取第一个处理者
     * @return
     */
    GatewayEntity getFirstGatewayEntity();
}

public class GatewayImpl implements GatewayDao {

    /**
     * 初始化,将枚举中配置的handler初始化到map中,方便获取
     */
    private static Map<Integer, GatewayEntity> gatewayEntityMap = new HashMap<>();

    static {
        GatewayEnum[] values = GatewayEnum.values();
        for (GatewayEnum value : values) {
            GatewayEntity gatewayEntity = value.getGatewayEntity();
            gatewayEntityMap.put(gatewayEntity.getHandlerId(), gatewayEntity);
        }
    }

    @Override
    public GatewayEntity getGatewayEntity(Integer handlerId) {
        return gatewayEntityMap.get(handlerId);
    }

    @Override
    public GatewayEntity getFirstGatewayEntity() {
        for (Map.Entry<Integer, GatewayEntity> entry : gatewayEntityMap.entrySet()) {
            GatewayEntity value = entry.getValue();
            //  没有上一个handler的就是第一个
            if (value.getPreHandlerId() == null) {
                return value;
            }
        }
        return null;
    }
}

public class GatewayHandlerEnumFactory {

    private static GatewayDao gatewayDao = new GatewayImpl();

    // 提供静态方法,获取第一个handler
    public static GatewayHandler getFirstGatewayHandler() {

        GatewayEntity firstGatewayEntity = gatewayDao.getFirstGatewayEntity();
        GatewayHandler firstGatewayHandler = newGatewayHandler(firstGatewayEntity);
        if (firstGatewayHandler == null) {
            return null;
        }

        GatewayEntity tempGatewayEntity = firstGatewayEntity;
        Integer nextHandlerId = null;
        GatewayHandler tempGatewayHandler = firstGatewayHandler;
        // 迭代遍历所有handler,以及将它们链接起来
        while ((nextHandlerId = tempGatewayEntity.getNextHandlerId()) != null) {
            GatewayEntity gatewayEntity = gatewayDao.getGatewayEntity(nextHandlerId);
            GatewayHandler gatewayHandler = newGatewayHandler(gatewayEntity);
            tempGatewayHandler.setNext(gatewayHandler);
            tempGatewayHandler = gatewayHandler;
            tempGatewayEntity = gatewayEntity;
        }
    // 返回第一个handler
        return firstGatewayHandler;
    }

    /**
     * 反射实体化具体的处理者
     * @param firstGatewayEntity
     * @return
     */
    private static GatewayHandler newGatewayHandler(GatewayEntity firstGatewayEntity) {
        // 获取全限定类名
        String className = firstGatewayEntity.getConference(); 
        try {
            // 根据全限定类名,加载并初始化该类,即会初始化该类的静态段
            Class<?> clazz = Class.forName(className);
            return (GatewayHandler) clazz.newInstance();
        } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }


}

public class GetewayClient {
    public static void main(String[] args) {
        GetewayHandler firstGetewayHandler = GetewayHandlerEnumFactory.getFirstGetewayHandler();
        firstGetewayHandler.service();
    }
}
 

结语

设计模式有很多,责任链只是其中的一种,我觉得很有意思,非常值得一学。设计模式确实是一门艺术,仍需努力呀!

 

更多好文章

  1. 《Spring 学习笔记.pdf》

  2. 《MySQL 学习笔记.pdf》

  3. 2021 版 java 高并发常见面试题汇总.pdf

  4. Idea 快捷键大全.pdf

Java充电社

Java充电社,专注分享Java技术干货,包括多线程、JVM、SpringBoot、SpringCloud、Dubbo、Zookeeper、Redis、架构设计、微服务、消息队列、Git、面试题、程序员攻略、最新动态等。

28篇原创内容

公众号

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

代码越写越乱?那是因为你没用责任链 的相关文章

随机推荐

  • rtsp实例及讲解

    rtsp是real time streaming protocol 按照我的理解为流媒体控制协议 协议双方的的编码类型和地址 以及对stream media的控制 play pause record 注意这里不要与RTCP协议搞混 rtcp
  • Mysql—修改用户密码(重置密码)

    Mysql 修改用户密码 重置密码 1 登录mysql 1 2 root localhost mysql uroot p123456 root localhost mysql hlocalhost uroot p123456 如果忘记密码
  • ASP.NET Core 运行原理剖析

    1 ASP NET Core 运行原理剖析 1 1 概述 1 2 文件配置 1 2 1 Starup文件配置 Configure ConfigureServices 1 2 2 appsetting json配置 1 3 处理管道 中间件
  • cesium绘制点、线、面

    cesium绘制点 线 面 地图地形上 点 let handler new Cesium ScreenSpaceEventHandler viewer scene canvas handler setInputAction function
  • 【超级无敌详细的黑马前端笔记!即时更新~】

    超级无敌详细的黑马前端笔记 即时更新 这个笔记 是我自己在同步学习黑马前端使用的 不可以商用哦 学习路径 基础概念铺垫 了解 认识网页 五大浏览器和渲染引擎 Web标准 HTML初体验 HTML的感知 HTML骨架结构 开发工具的使用 语法
  • 【08】STM32·HAL库开发-HAL库介绍

    目录 1 初识HAL库 了解 1 1CMSIS简介 1 2HAL库简介 2 STM32Cube固件包浅析 了解 2 1如何获取STM32Cube固件包 2 2STM32Cube固件包文件夹简介 2 3CMSIS文件夹关键文件 2 3 1CM
  • 增量式pid分析 及 参数整定

    函数功能 增量PI控制器 1 入口参数 编码器测量值 目标速度 2 入口参数 编码器位置 目标位置 返回 值 电机PWM 根据增量式离散PID公式 pwm Kp e k e k 1 Ki e k Kd e k 2e k 1 e k 2 e
  • 宝塔Linux面板—请使用正确的入口登录面板

    请使用正确的入口登录面板 错误原因 当前新安装的已经开启了安全入口登录 新装机器都会随机一个8位字符的安全入口名称 亦可以在面板设置处修改 如您没记录或不记得了 可以使用以下方式解决 解决方法 1 在SSH终端输入以下一种命令来解决 登录你
  • C# 中 KeyPress 、KeyDown 和KeyPress的区别

    1 KeyPress主要用来捕获数字 注意 包括Shift 数字的符号 字母 注意 包括大小写 小键盘等除了F1 12 SHIFT Alt Ctrl Insert Home PgUp Delete End PgDn ScrollLock P
  • 将时间写入数据库时,秒带小数点问题

    1 问题原因 new Date 时间秒带小数点 2 解决思路 将new Date 格式化为年月日时分秒字符串 在将该字符串转为Date 3 示例 Constant类 public final static SimpleDateFormat
  • VScode中文注释乱码问题解决

    VScode默认是用utf 8打开工程代码 C语言里的中文注释如果是Source insight之前gbk编码的注释可能会显示乱码 如何能让代码打开gbk编码的文件也不乱码 设置VScode如下 方法一 依次打开 文件 首选项 设置 然后搜
  • 电机转角控制算法

    时间周期是1 10ms可调 橙色和绿色代表期望和真实速度 红色代表期望角度 紫色代表电机转角 蓝色是减速机输出角度 在9700时刻角度已到达期望角度 速度由 200还未到0 所以算法上需要在要到达目标前某值就需要提前减速 这个值和当前真实速
  • MySQL查询进阶

    多表查询 ALLSOME查询 聚集函数查询 分组查询 分组过滤查询 Student表格 Dept 院系 学院号 学院名 院长 Course表格 Teacher表格 教师号 教师姓名 部门号 工资 SC表格 学号 课程号 分数 反应学生和课程
  • 使用线程池创建线程

    使用线程池可以不用线程的时候放回线程池 用的时候再从线程池取 1 5后引入的Executor框架的最大优点是把任务的提交和执行解耦 Executor接口中定义了一个方法execute 该方法接收一个Runable实例 它用来执行一个任务 任
  • IDEA插件系列(10):Statistic插件——统计代码行数

    1 插件介绍 显示项目统计信息 此插件显示按扩展名排序的文件 以及大小 行数LOC等 2 安装方式 第一种安装方式是使用IDEA下载插件进行安装 第二种方式是使用离线插件进行安装 插件下载地址 http plugins jetbrains
  • W. Richard Stevens Unix网络编程 作品集

    W Richard Stevens 写的那三卷书以怎样的顺序看是比较好的 按我的经验来看先粗略的看一遍卷一 然后再结合卷一看卷二 卷二要看几遍 每遍都会有收获 然后卷三大概看看就行 之后就是看源码 看bsd lite的 在最后就是看linu
  • svn客户端Tortoise SVN使用方法

    svn客户端Tortoise SVN使用方法 转载自 http www cnblogs com armyfai p 3985660 html 该博主介绍比较详细 这里只转载其中svn客户端使用部分 1 首先我们需要下载 svn小乌龟 后 进
  • Webservice实践(二)Webservice 客户端开发

    现在我们首先进行客户端开发的实践 从客户端实践来了解一下webservice的应用场景 比如说现在已经有一个webservice服务 提供的翻译方面的功能服务 主要是免费的webservice接口现在很多都被封了 我们需要编写一个客户端来使
  • Caffe中计算图像均值的实现(cifar10)

    在深度学习中 在进行test时经常会减去train数据集的图像均值 这样做的好处是 属于数据预处理中的数据归一化 降低数据间相似性 可以将数值调整到一个合理的范围 以下code是用于计算cifar10中训练集的图像均值 include fu
  • 代码越写越乱?那是因为你没用责任链

    路人 Java充电社 2022 08 04 08 06 发表于上海 收录于合集 java充电社244个 大家好 我是路人 最近 我让团队内一位成员写了一个导入功能 他使用了责任链模式 代码堆的非常多 bug 也多 没有达到我预期的效果 实际