使用场景:多个连续的功能上不相互依赖的处理环节,共同完成一项任务。
特点:(1)顺序执行
(2) 有多个处理环节
比较:与观察者模式不同的是,观察者模式中所有的订阅者可并行执行,而责任链模式具有顺序执行的特点;
其次观察者模式中所有的订阅者没有任何关联,而责任链模式中的每个处理环节具有传递性。
模式举例:
(1)公共接口
public interface StrategyInterface { void execute(Object obj); }
(2)抽象实现类
@Data public abstract class AbstractStrategy implements StrategyInterface{ protected StrategyInterface strategyInterface; public void next(Object obj){ if (strategyInterface != null){ strategyInterface.execute(obj); } } }
(3)实现类-第一环节
@Slf4j @Component public class StrategyHandle extends AbstractStrategy { @Override public void execute(Object obj) { try { log.info("first StrategyHandle task begin..... "); next(obj); successHandle(obj); }catch (Exception e){ errorHandle(obj); } } private void successHandle(Object obj) { log.info("first task success over"); } private void errorHandle(Object obj) { log.error("first task error"); } }
(4)实现类-第二环节
@Slf4j @Component public class StrategyCheck extends AbstractStrategy { @Override public void execute(Object obj) { log.info("second StrategyCheck task begin......"); checkBefore(obj); next(obj); checkAfter(obj); } private void checkAfter(Object obj) { log.info("second StrategyCheck task 后置校验"); } private void checkBefore(Object obj) { log.info("second StrategyCheck task 前置校验"); } }
(5)实现类-第三环节
@Slf4j @Component public class StrategyCalculate extends AbstractStrategy { @Override public void execute(Object obj) { log.info("third StrategyCalculate task begin......"); calculate(obj); next(obj); } public void calculate(Object obj){ log.info("third 执行任务。。。"); } }
(6)组装链式调用
@Service public class StrategyService { @Autowired StrategyHandle strategyHandle; @Autowired StrategyCheck strategyCheck; @Autowired StrategyCalculate strategyCalculate; public void execute(Object obj){ strategyHandle.setStrategyInterface(strategyCheck); strategyCheck.setStrategyInterface(strategyCalculate); strategyCalculate.setStrategyInterface(null); strategyHandle.execute(obj); } }
(7)测试
@SpringBootTest @Slf4j class Demo17ApplicationTests { @Autowired StrategyService strategyService; @Test void contextLoads() { strategyService.execute(new Object()); } }