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

责任链模式(Chain of Responsibility)

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

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

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

缺点:

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

应用场景

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值