设计模式 - 责任链模式(Chain of Responsibility)--链式处理

tech2025-08-08  16

责任链模式(Chain of Responsibility)

应用场景类结构图代码实现

将链中的每个节点看作一个对象,各节点处理的请求都不同,且自动维护下一个节点对象。

当一个请求从链首发出时,会沿着链的路径传递给每一个节点对象,知道有对象处理该请求为止。

责任链模式主要是为了解耦请求和处理,客户只需要将请求发送到链上即可,无需关心处理细节,符合开闭原则。

缺点:

责任链太长或者处理时间太长,会影响整体性能。节点循环使用,容易造成死循环。

应用场景

1)有多个对象可以处理一个请求,具体哪个对象处理由运行时刻自动决定。 2)可动态指定一组对象处理请求,这一组对象可动态添加。 3)不明确该交给哪个对象处理时,向多个对象提交同一请求。

比如: 登录前的数据验证

类结构图

代码实现

定义一个抽象父类 Leader ,并持有 Leader 属性,通过构造,搭建好 责任链中下一个节点的 模型。

public abstract class Leader { protected Leader nextLeader; public Leader(Leader leader) { this.nextLeader = leader; } abstract void examine(int days); }

实现类,作为一个节点(一)

public class GroupLeaderImpl extends Leader { public GroupLeaderImpl(Leader leader) { super(leader); } @Override public void examine(int days) { if (days <= 3) { System.out.println("组长批假" + days + "天"); } else { nextLeader.examine(days); } } }

实现类,作为一个节点(二)

public class DepartmentLeaderImpl extends Leader { public DepartmentLeaderImpl(Leader leader) { super(leader); } @Override public void examine(int days) { if (days <= 5) { System.out.println("部门领导批假" + days + "天"); } else { nextLeader.examine(days); } } }

实现类,作为一个节点(三)

public class ManagerLeaderImpl extends Leader { public ManagerLeaderImpl(Leader leader) { super(leader); } @Override public void examine(int days) { System.out.println("经理批假" + days + "天"); } }

测试类,搭建责任链中 各节点的上下级关系。

public class Client { public static void main(String[] args) { Leader manager = new ManagerLeaderImpl(null); Leader department = new DepartmentLeaderImpl(manager); Leader group = new GroupLeaderImpl(department); group.examine(1); group.examine(4); group.examine(7); } }

输出结果: 组长批假1天 部门领导批假4天 经理批假7天

最新回复(0)