概念
顾名思义,责任链模式(Chain of Responsibility Pattern)为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。
在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
参考链接: https://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html
代码案例
写个要钱抽象类
/** * 要钱接口 */ public abstract class AskMoney { protected double howMuch; /** * 下一个元素 */ protected AskMoney askMoneyNext; public void setAskMoneyNext(AskMoney askMoneyNext) { this.askMoneyNext = askMoneyNext; } /** * 要钱逻辑 * @param howMuchMoney * @return */ public String ask(double howMuchMoney){ String ask = null; //如果钱够,直接要,如果不够找下一个 if (howMuch<=howMuchMoney){ ask = askForWho(howMuchMoney); }else { if (Objects.nonNull(askMoneyNext)){ ask = askMoneyNext.ask(howMuchMoney); } } return ask; } /** * 找谁要 * @param howMuchMoney * @return */ abstract protected String askForWho(double howMuchMoney); }
两个继承的子类
向父亲要
/** * 向父亲要钱 */ @Slf4j public class AskMoneyForFather extends AskMoney { public AskMoneyForFather(double howMuch) { this.howMuch=howMuch; } @Override protected String askForWho(double howMuchMoney) { log.info("给老爸要 {}",howMuchMoney); return "给老爸要 "+howMuchMoney; } }
向母亲要
/** * 向母亲要钱 */ @Slf4j public class AskMoneyForMother extends AskMoney { public AskMoneyForMother(double howMuch) { this.howMuch=howMuch; } @Override protected String askForWho(double howMuchMoney) { log.info("给老妈要 {}",howMuchMoney); return "给老妈要 "+howMuchMoney; } }
/** * 责任链工具类,组装查找层级 */ public class ResponsibilityChainUtil { public static AskMoney getChainOf(){ AskMoney askMoneyFa= new AskMoneyForFather(1000); AskMoney askMoneyMo= new AskMoneyForMother(500); askMoneyFa.setAskMoneyNext(askMoneyMo); return askMoneyFa; } }
测试主类
/** * 设计模式控制器 */ @RestController @RequestMapping("/designPattern") @Slf4j public class DesignController { @PostMapping("/responsibilitychain") public ResponseModel responsibilitychain(@RequestBody List<Double> howMuch) { log.info("responsibilitychain ---- start "); AskMoney chainOf = ResponsibilityChainUtil.getChainOf(); List<String> list = new ArrayList<>(); for (Double much : howMuch) { list.add(chainOf.ask(much)); } log.info("responsibilitychain ---- end "); return new ResponseModel("责任链模式完成", 200,list); } }
测试案例
2022-06-26 19:27:34.953 INFO responsibilitychain ---- start 【http-nio-8081-exec-2】【DesignController:67】 2022-06-26 19:27:39.786 INFO 给老妈要 600.0 【http-nio-8081-exec-2】【AskMoneyForMother:15】 2022-06-26 19:27:39.787 INFO 给老爸要 4000.0 【http-nio-8081-exec-2】【AskMoneyForFather:15】 2022-06-26 19:27:39.788 INFO responsibilitychain ---- end 【http-nio-8081-exec-2】【DesignController:73】