位置: IT常识 - 正文

同事写了一个责任链模式,bug 无数...

编辑:rootadmin
背景 最近,我让团队内一位成员写了一个导入功能。他使用了责任链模式,代码堆的非常多,bug 也多,没有达到我预期的效果。 实际上,针对导入功能,我认为模版方法更合适!为此,隔壁团队也拿出我们的案例,进行了集体 code review。 学好设计模式,且不要为了练习,强行使用!让原本 100 行就能实 ... 背景

推荐整理分享同事写了一个责任链模式,bug 无数...,希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:,内容如对您有帮助,希望把文章链接给更多的朋友!

最近,我让团队内一位成员写了一个导入功能。他使用了责任链模式,代码堆的非常多,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(); } } }}同事写了一个责任链模式,bug 无数...

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

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

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

更多设计模式系列教程:https://www.javastack.cn/

| 初步改造

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

这样客户端就不需要进行多重 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(); }}

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

版权

本文链接地址:https://www.jiuchutong.com/zhishi/304792.html 转载请保留说明!

上一篇:一起爬山吗?《隐秘的角落》为什么译成Cat's Cradle?(你要和我一起爬山吗)

下一篇:php使用array_diff去除元素(php使用while循环计算1到100的和)

  • 支付宝健康码怎么添加孩子的(支付宝健康码怎么解除绑定)

    支付宝健康码怎么添加孩子的(支付宝健康码怎么解除绑定)

  • 苹果腾讯会议录屏为什么没有声音(苹果腾讯会议录音)

    苹果腾讯会议录屏为什么没有声音(苹果腾讯会议录音)

  • 微信打招呼频率过高怎么办(微信打招呼频率过高会封号吗)

    微信打招呼频率过高怎么办(微信打招呼频率过高会封号吗)

  • 荣耀9x有什么特殊功能(荣耀9x有什么特别功能)

    荣耀9x有什么特殊功能(荣耀9x有什么特别功能)

  • ppt虚线怎么添加(ppt虚线怎么添加框)

    ppt虚线怎么添加(ppt虚线怎么添加框)

  • 抖音小小洗衣机是什么(小小洗衣机现在叫什么)

    抖音小小洗衣机是什么(小小洗衣机现在叫什么)

  • 最大预渲染设置1还是4(最大预渲染帧)

    最大预渲染设置1还是4(最大预渲染帧)

  • x9plus什么时候上市的(x9splus现在价)

    x9plus什么时候上市的(x9splus现在价)

  • 小米商城催单后多久发货(小米商城催单后怎么取消)

    小米商城催单后多久发货(小米商城催单后怎么取消)

  • 骁龙865什么时候出(骁龙865什么时候出的)

    骁龙865什么时候出(骁龙865什么时候出的)

  • 华为微信图标有个盾牌(华为微信图标有个蓝色对勾)

    华为微信图标有个盾牌(华为微信图标有个蓝色对勾)

  • 数据库管理系统是什么(数据库管理系统有哪些)

    数据库管理系统是什么(数据库管理系统有哪些)

  • 图片设置四周型环绕怎么设置(图片设置四周型环绕位置为两边)

    图片设置四周型环绕怎么设置(图片设置四周型环绕位置为两边)

  • 微信一年封几次就永久(微信解封方法)

    微信一年封几次就永久(微信解封方法)

  • i3i5区别(i3 i5 区别)

    i3i5区别(i3 i5 区别)

  • 小新14和air14是一样吗(小新14和air14区别)

    小新14和air14是一样吗(小新14和air14区别)

  • vivo红外功能怎么打开(vivo红外功能怎么弄)

    vivo红外功能怎么打开(vivo红外功能怎么弄)

  • 美团订后砍五折怎么砍(美团订单5折退款)

    美团订后砍五折怎么砍(美团订单5折退款)

  • 微信自动扣费怎么恢复(微信自动扣费怎么取消解约)

    微信自动扣费怎么恢复(微信自动扣费怎么取消解约)

  • 苹果手机a1688是什么版本(苹果手机a1860是什么意思)

    苹果手机a1688是什么版本(苹果手机a1860是什么意思)

  • 电脑微信的聊天记录怎么寻找在哪个文件夹(电脑微信的聊天记录)

    电脑微信的聊天记录怎么寻找在哪个文件夹(电脑微信的聊天记录)

  • 微信服务通知怎么恢复(微信服务通知怎么关闭)

    微信服务通知怎么恢复(微信服务通知怎么关闭)

  • 笔记本连接投影仪没有声音(笔记本连接投影仪不显示电脑画面)

    笔记本连接投影仪没有声音(笔记本连接投影仪不显示电脑画面)

  • 2015年4月4日摄于Tear Drop Arch附近的月全食,犹他州纪念碑谷 (© Alan Dyer/Alamy)

    2015年4月4日摄于Tear Drop Arch附近的月全食,犹他州纪念碑谷 (© Alan Dyer/Alamy)

  • 最领先的固态硬盘工艺是什么(2021最好的固态)

    最领先的固态硬盘工艺是什么(2021最好的固态)

  • 页面访问升级出错怎么解决(页面访问升级出错怎么办)

    页面访问升级出错怎么解决(页面访问升级出错怎么办)

  • 退回企业所得税的账务处理
  • 公司注销前欠客户钱
  • 普票加专票超过30万全交税吗2020
  • 出口免税不退税会计分录
  • 小规模纳税人开票税率
  • 手撕定额发票不是免税怎么还报税
  • 准则依据
  • 小微企业增值税免税政策2023年
  • 预付房租的会计科目
  • 土地增值税纳税地点
  • 公司装修费用必须交税吗
  • 销售方针有哪些
  • 粮食仓储设施设备管理
  • 同一地级行政区怎么划分
  • 提供物业管理服务的纳税人如何认定
  • 多缴税款退回及退回
  • 项目自筹资金是什么意思
  • 公司利润如何分配到个人
  • 员工产假期间工资是社保局发吗
  • win7不能进系统怎么办
  • 挖机所有权需要办理什么手续吗
  • 财产租赁所得个人所得税怎么申报
  • 其他应付款无法支付的账务处理方法
  • 现金日记账漏记去年的利息怎么算
  • 垫资计入什么会计科目
  • 正版的win10多少钱
  • win7纯净版系统官网
  • vue3自定义指令
  • 贷款减值准备什么科目
  • 分红派息钱去哪里了
  • 混合销售与兼营行为的区别
  • php抓取网页图片
  • 包装费 增值税
  • 自动驾驶决策规划技术理论与实践电子版
  • python优化工具箱
  • Python如何检测两个相同的列表
  • In Java, how do I read/convert an InputStream to a String? Stack Overflow
  • electron开发的应用程序
  • 新旧所得税法转换规定
  • 税票抵扣是多少个点
  • 员工福利费的账务处理
  • sql多条记录取一条
  • sql server 2008怎么使用sql语句
  • 发票开9个点
  • 筹建期间的开办费为什么不属于资产
  • 专利权的入账价值包括资本化支出吗
  • 销售赠品的会计分录
  • 自己开发建造的房屋
  • 冲销凭证如何做分录
  • 零余额账户出纳日记账
  • 企业增资的流程
  • 企业预付账款怎么做账
  • 在MySQL中使用GTIDs复制协议和中断协议的教程
  • sqlserver CONVERT()函数用法小结
  • 同一个sql语句 连接两个数据库服务器
  • linux怎么统计文件中出现字符串的数量
  • 在幻灯片母版中
  • solaris如何关闭usb接口
  • 主板不支持u盘装系统怎么办
  • win10无internet怎么办
  • win7一直配置
  • win10内置管理员账户禁用
  • win10系统中怎么设置搜狗输入
  • 自动化软件安装工具
  • 批处理 /b
  • Node.js中的全局变量有哪些
  • unity linux arm
  • react 系列
  • js的settimeout方法
  • jQuery实现checkbox列表的全选、反选功能
  • nodejs 模块
  • javascript性能优化写法
  • js实现全屏
  • unity ulua
  • vs开发unity教程
  • 用jquery写注册界面
  • python 命令
  • jquery获取php变量
  • 税务开票系统对账流程
  • 办税人员怎么绑定电子税务系统
  • 免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

    鄂ICP备2023003026号

    网站地图: 企业信息 工商信息 财税知识 网络常识 编程技术

    友情链接: 武汉网站建设