背景
最近,我让团队内一位成员写了一个导入性能。他应用了责任链模式,代码堆的十分多,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关通过){ //... } } } } }}
这种代码不仅冗余,并且当咱们要将某两关进行调整时会对代码十分大的改变,这种操作的危险是很高的,因而,该写法十分蹩脚。
更多设计模式系列教程: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(); }}
设计模式有很多,责任链只是其中的一种,我觉得很有意思,十分值得一学。设计模式的确是一门艺术,仍需致力呀!
版权申明:本文为CSDN博主「Java小海.」的原创文章,遵循CC 4.0 BY-SA版权协定,转载请附上原文出处链接及本申明。原文链接:https://blog.csdn.net/q147275...
近期热文举荐:
1.1,000+ 道 Java面试题及答案整顿(2022最新版)
2.劲爆!Java 协程要来了。。。
3.Spring Boot 2.x 教程,太全了!
4.别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!
5.《Java开发手册(嵩山版)》最新公布,速速下载!
感觉不错,别忘了顺手点赞+转发哦!