经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » 设计模式 » 查看文章
责任链模式的实践
来源:cnblogs  作者:xuanhaoo  时间:2021/5/31 9:09:49  对本文有异议

责任链模式

基本概念

 责任链(Chain of Responsibility)模式的定义:为了避免请求发送者与多个请求处理者耦合在一起,于是将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链;当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。

关于责任链的详细介绍可以点击这里进行了解。就不在这里过多叙述啦。

 要来就来点实际的干货:在做公司项目(会员积分商城)项目时,会员模块有个会员降级任务,在开发这个功能的时候,我就将责任链模式集合业务融入了进去。

 结合业务模式,降级策略配置有三个条件,当这三个条件有一满足则不执行降级,所以如果用if/else来操作那么应该会写很多,且逻辑不清晰,不够优雅。适当的运用设计模式,使逻辑清晰明了,也方便后续同学阅读。

  业务的整体流程图如下:

  抽象的职责节点的UML图如下:

  上代码实战看看:

部分代码使用Test表示啦,大家都懂的哦

  • 基础接口:BaseChainHandle.java
  1. public interface BaseChainHandle {
  2. /**
  3. * 责任type
  4. * @return
  5. */
  6. Integer getChainType();
  7. }
  • 抽象父类:AbstractRelegationChainHandle.java
  1. public abstract class AbstractRelegationChainHandle implements BaseChainHandle {
  2. /**
  3. * 下一个节点
  4. */
  5. private AbstractRelegationChainHandle nextChain;
  6. /**
  7. * 对外暴露方法
  8. * @return
  9. */
  10. public abstract boolean execute(RelegationChainDTO dto);
  11. public AbstractRelegationChainHandle getNextChain() {
  12. return nextChain;
  13. }
  14. public AbstractRelegationChainHandle setNextChain(AbstractRelegationChainHandle nextChain) {
  15. this.nextChain = nextChain;
  16. return this.nextChain;
  17. }
  18. public AbstractRelegationChainHandle getCurChain() {
  19. return this;
  20. }
  21. }
  • 空节点子类:

设置该节点的意义主要是为了构造链表时的初始化首节点。

  1. @Component
  2. public class NotChainHandle extends AbstractRelegationChainHandle{
  3. /**
  4. * 设置空节点的意义是:该节点作为起始节点,不做任何操作,仅构造责任实例联时使用
  5. * @return
  6. */
  7. @Override
  8. public Integer getChainType() {
  9. return -1;
  10. }
  11. @Override
  12. public boolean execute(RelegationChainDTO dto) {
  13. if (Objects.nonNull(this.getNextChain())) {
  14. // 向下传递
  15. return this.getNextChain().execute(dto);
  16. } else {
  17. return Boolean.FALSE;
  18. }
  19. }
  20. }
  • 具体逻辑节点子类:(其他责任节点类似,不再枚举)
  1. package com.test;
  2. @Slf4j
  3. @Component
  4. public class Test1Handle extends AbstractRelegationChainHandle {
  5. @Override
  6. public Integer getChainType() {
  7. return RelegationStrategyEnum.Test1.getCode();
  8. }
  9. @SneakyThrows
  10. @Override
  11. public boolean execute(RelegationChainDTO dto) {
  12. // 业务逻辑处理...
  13. if (Objects.nonNull(mkRecordTO)) {
  14. if (//condition) {
  15. return Boolean.TRUE;
  16. }
  17. }
  18. if (Objects.nonNull(this.getNextChain())) {
  19. // 向下传递
  20. return this.getNextChain().execute(dto);
  21. } else {
  22. return Boolean.FALSE;
  23. }
  24. }
  25. }
  • 在工厂中将节点bean实例化,类似于策略模式使用@Autowire自动注入
  1. package com.test;
  2. /**
  3. * @description 会员保级责任链 装配节点工厂
  4. */
  5. @Component
  6. public class RelegationChainHandleFactory {
  7. /**
  8. * 自动注入节点进来:必须是String,因为自动注入会将beanName设置为String
  9. */
  10. @Autowired
  11. private Map<String, AbstractRelegationChainHandle> relegationChainMap;
  12. private final Map<Integer, AbstractRelegationChainHandle> relegationChainMapContext = new HashMap<>();
  13. @PostConstruct
  14. public void setRelegationChainMap() {
  15. for (AbstractRelegationChainHandle obj : relegationChainMap.values()) {
  16. relegationChainMapContext.put(obj.getChainType(), obj);
  17. }
  18. }
  19. public AbstractRelegationChainHandle getChainHandleContext(Integer type) {
  20. return relegationChainMapContext.get(type);
  21. }
  22. }
  • 在业务逻辑中构造责任链:并执行节点逻辑

请看下方代码:为什么要初始化一个ThreadLocal变量来保存责任链:初始化一个ThreadLocal变量来保存该次动态责任链十分重要,具体原因可见代码中的相关注释内容。

  1. package com.test;
  2. ......
  3. /**
  4. * 每一个子线程储存降级的动态责任链
  5. */
  6. private ThreadLocal<AbstractRelegationChainHandle> startChain = new ThreadLocal<>();
  7. .......
  8. private void downLevelTest(Dto dto) {
  9. // ... 业务逻辑处理
  10. // 2. 匹配保级规则
  11. // 2.1 构建保级规则责任链
  12. /**
  13. * 使用ThreadLocal储存该子线程的责任链:因为Spring实例化bean默认单例的,多线程环境下,bean的实例会被多个线程获取,
  14. * 造成安全问题,所以使用ThreadLocal为每一个子线程分配一个空间,保存每一个子线程的动态责任链,隔离线程
  15. */
  16. // 装载责任链节点
  17. // 初始化责任链开始节点 type: -1
  18. startChain.set(relegationChainHandleFactory.getChainHandleContext(-1));
  19. // 手动置空:因为当其他线程实例化的该责任节点类的next可能会已经存在数据,我们要动态拼装责任链(下同)
  20. startChain.get().setNextChain(null);
  21. for (int i = 0; i < relegationStrategy.size(); i++) {
  22. // 构造责任链:类似于构造链表的方式
  23. // TODO 通过switch case不太优雅,目前暂时想到使用该方法进行构造责任链,待优化
  24. // 尝试过其他写法来拼装(使用临时变量(多个ThreadLocal)等)
  25. switch (i) {
  26. case 0:
  27. startChain.get().setNextChain(relegationChainHandleFactory.getChainHandleContext(relegationStrategy.get(i)));
  28. startChain.get().getNextChain().setNextChain(null);
  29. break;
  30. case 1:
  31. startChain.get().getNextChain()
  32. .setNextChain(relegationChainHandleFactory.getChainHandleContext(relegationStrategy.get(i)));
  33. startChain.get().getNextChain().getNextChain().setNextChain(null);
  34. break;
  35. case 2:
  36. startChain.get().getNextChain().getNextChain()
  37. .setNextChain(relegationChainHandleFactory.getChainHandleContext(relegationStrategy.get(i)));
  38. startChain.get().getNextChain().getNextChain().getNextChain().setNextChain(null);
  39. break;
  40. default:
  41. }
  42. }
  43. // ... 业务处理
  44. } catch (Exception e) {
  45. log.info("处理任务发生异常,account:{},e:{}", account, e);
  46. } finally {
  47. startChain.remove();
  48. }
  49. }

有些写法虽然也不太优雅,请见谅哈,鄙人水平有限,还需要多加学习!欢迎大家指出来一起探讨探讨

总结

 设计模式虽然让代码看起来变多了很多,但是这样写可以使我们的逻辑清晰,并且方便扩展,提高代码的健壮性。
但有个问题需要提醒大家,在平时的开发过程中不能为了设计而设计,这样就会造成过度设计,反而起反作用,一定要结合自身业务来考虑,技术也是为了实现业务而服务的。

原文链接:http://www.cnblogs.com/xuanhaoo/p/14815216.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号