描述:菜鸟教程地址:https://www.runoob.com/design-pattern/chain-of-responsibility-pattern.html(案例也是菜鸟上的案例)
- 介绍呢,可以看一下菜鸟上的介绍。大体意思是说:为了解偶,在请求的链路上 用多个 对象 处理不同的事情, 这些对象使用链式存储结构,形成一个链,对象挨个执行(可以执行某个)。
- 缺点:一条链路上对象的对象太多了、不容易维护啊、不能保证请求一定被接收(每个对象处理一部分逻辑,可能整个链路走完了也没有合适的对象来处理这个请求,这里需要提供一个默认的处理逻辑)
- 使用场景:菜鸟上的案例(日志的处理级别)、审批系统(组长审核、经理....),java 过滤器 filter 底层实现、
- 对菜鸟上的案例,做了一点点改造:(模拟 从数据库里读取 初始化链路中的对象)注意:(对象 提供 无参构造,getset方法)
private static AbstractLogger simulationDB(AbstractLogger firstLogger) throws Exception { Map<Integer,String> map = new HashMap<>(); map.put(AbstractLogger.ERROR,"com.mayikt.simulation.FileLogger"); map.put(AbstractLogger.DEBUG,"com.mayikt.simulation.ConsoleLogger"); map.put(AbstractLogger.INFO,null); int level = firstLogger.getLevel(); AbstractLogger nextLogger = firstLogger; while (map.get(level) != null){ String classAddr = map.get(level); AbstractLogger newNext = (AbstractLogger) Class.forName(classAddr).newInstance(); level --; newNext.setLevel(level); nextLogger.setNextLogger(newNext); nextLogger = newNext; } return firstLogger; }
代码地址:https://gitee.com/ginseng_fruit_lost/xwTestJava/tree/master/simulation(1)