设计模式(二十)之行为型模式--职责链模式

一、职责链模式

1、案例

1.1 OA系统采购审批需求

学校OA系统的采购审批项目:需求是:

  1. 采购员采购教学器材
  2. 如果金额 小于等于5000, 由教学主任审批(0 <= x <= 5000)
  3. 如果金额 小于等于10000, 由院长审批(5000 <= x <= 10000)
  4. 如果金额 小于等于30000, 由副校长审批(10000 <= x <= 30000)
  5. 如果金额 超过30000以上, 由校长审批(30000 <= x )

请设计程序完成采购审批项目

1.2 传统方案

传统方式:接收到一个采购请求后,根据采购金额来调用对应的Approver(审批人)完成审批

1.3 传统方案问题分析

  1. 客户端这里会使用到分支判断(比如switch)来对不同的采购请求处理,这样就存在如下问题:(1)如果各个级别的人员的审批金额发生变化,在客户端的也需要变化(2)客户端必须明确的指定 有多个审批级别和访问
  2. 这样 对一个采购请求进行处理和Approver(审批人)就存在强耦合关系,不利于代码的扩展和维护
  3. 解决方案=> 职责链模式

2、职责链模式基本介绍

2.1 基本介绍

  1. 职责链模式(Chain of Responsibility Pattern):又叫责任链模式,为请求创建了一个 接收者对象的链。这种模式对请求的发送者和接收者进行解耦
  2. 职责链模式通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者。以此类推

2.2 原理类图

image-20210815230454695

职责链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系,将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止

  1. Handler:抽象的处理者,定义了一个处理请求的接口,同时含有另外的Handler
  2. ConcreteHandlerA,B是具体的处理者,处理它自己负责的请求,可以访问它的后继者(即下一个处理者),如果可以处理当前请求,则处理,否则,将该请求交给 后继者去处理,从而行为一个职责链
  3. Request:含有很多属性,表示一个请求

3、代码实例

3.1 代码类图

image-202108152311009613.2 代码

3.2.1 PurchaseRequest类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class PurchaseRequest {
private int type;//请求类型
private float price = 0.0f;
private int id = 0;

public PurchaseRequest(int type, float price, int id) {
this.type = type;
this.price = price;
this.id = id;
}

public int getType() {
return type;
}

public float getPrice() {
return price;
}

public int getId() {
return id;
}
}

3.2.2 Approver抽象类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public abstract class Approver {

Approver approver;//下一个处理者
String name;//名字

public Approver(String name) {
this.name = name;
}

// 下一个处理者
public void setApprover(Approver approver) {
this.approver = approver;
}

//处理审批请求的方法,得到一个请求,处理是子类完成,因此该方法做成抽象
public abstract void processRequest(PurchaseRequest purchaseRequest);
}

3.2.3 DepartmentApprover 类

继承Approver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class DepartmentApprover extends Approver {
public DepartmentApprover(String name) {
super(name);
}

@Override
public void processRequest(PurchaseRequest purchaseRequest) {
if(purchaseRequest.getPrice() <= 5000){
System.out.println(" 请求编号 id= "+purchaseRequest.getId() + " 被 " +this.name + " 处理");
}else{
approver.processRequest(purchaseRequest);
}
}
}

3.2.4 CollegeApprover类

继承Approver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class CollegeApprover extends Approver {
public CollegeApprover(String name) {
super(name);
}

@Override
public void processRequest(PurchaseRequest purchaseRequest) {
if(purchaseRequest.getPrice() > 5000 && purchaseRequest.getPrice() <= 10000){
System.out.println(" 请求编号 id= "+purchaseRequest.getId() + " 被 " +this.name + " 处理");
}else{
approver.processRequest(purchaseRequest);
}
}
}

3.2.5 ViceSchoolMasterApprover类

继承Approver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ViceSchoolMasterApprover extends Approver {

public ViceSchoolMasterApprover(String name) {
super(name);
}

@Override
public void processRequest(PurchaseRequest purchaseRequest) {
if(purchaseRequest.getPrice() > 10000 && purchaseRequest.getPrice() <= 30000){
System.out.println(" 请求编号 id= "+purchaseRequest.getId() + " 被 " +this.name + " 处理");
}else{
approver.processRequest(purchaseRequest);
}
}
}

3.2.6 SchoolMasterApprover类

继承Approver

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class SchoolMasterApprover extends Approver {
public SchoolMasterApprover(String name) {
super(name);
}

@Override
public void processRequest(PurchaseRequest purchaseRequest) {
if(purchaseRequest.getPrice() > 30000){
System.out.println(" 请求编号 id= "+purchaseRequest.getId() + " 被 " +this.name + " 处理");
}else{
approver.processRequest(purchaseRequest);
}
}
}

3.2.7 Client类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Client {
public static void main(String[] args) {
// 创建一个请求
PurchaseRequest purchaseRequest = new PurchaseRequest(1, 31000, 1);

// 创建相关的审批人
DepartmentApprover departmentApprover = new DepartmentApprover("张主任");
CollegeApprover collegeApprover = new CollegeApprover("李院长");
ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("王副校长");
SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("周校长");

// 需要将各个审批级别的下一个设置好(如果没有该审批级别,在最后departmentApprover.processRequest(purchaseRequest) 会直接报空指针异常)
departmentApprover.setApprover(collegeApprover);
collegeApprover.setApprover(viceSchoolMasterApprover);
viceSchoolMasterApprover.setApprover(schoolMasterApprover);
//如果不设置如下代码,则直接使用schoolMasterApprover.processRequest(purchaseRequest) 处理请求时,会报错,因此要成环状
schoolMasterApprover.setApprover(departmentApprover);
departmentApprover.processRequest(purchaseRequest);
//schoolMasterApprover.processRequest(purchaseRequest);
}
}

结果:

1
请求编号 id= 1 被 周校长 处理

分析:

(1)若屏蔽如下代码

1
2
3
4
5
departmentApprover.setApprover(collegeApprover);
collegeApprover.setApprover(viceSchoolMasterApprover);
viceSchoolMasterApprover.setApprover(schoolMasterApprover);
//如果不设置如下代码,则直接使用schoolMasterApprover.processRequest(purchaseRequest) 处理请求时,会报错,因此要成环状
schoolMasterApprover.setApprover(departmentApprover);

即将代码修改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Client {
public static void main(String[] args) {
// 创建一个请求
PurchaseRequest purchaseRequest = new PurchaseRequest(1, 31000, 1);

// 创建相关的审批人
DepartmentApprover departmentApprover = new DepartmentApprover("张主任");
CollegeApprover collegeApprover = new CollegeApprover("李院长");
ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("王副校长");
SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("周校长");

// 需要将各个审批级别的下一个设置好(如果没有该审批级别,在最后departmentApprover.processRequest(purchaseRequest) 会直接报空指针异常)
// departmentApprover.setApprover(collegeApprover);
// collegeApprover.setApprover(viceSchoolMasterApprover);
// viceSchoolMasterApprover.setApprover(schoolMasterApprover);
// //如果不设置如下代码,则直接使用schoolMasterApprover.processRequest(purchaseRequest) 处理请求时,会报错,因此要成环状
// schoolMasterApprover.setApprover(departmentApprover);
departmentApprover.processRequest(purchaseRequest);
//schoolMasterApprover.processRequest(purchaseRequest);
}
}

则会报空指针异常,因为还没有指定下一个的接收者

1
2
3
Exception in thread "main" java.lang.NullPointerException
at com.ldg.GoF23.reponsiabliity.DepartmentApprover.processRequest(DepartmentApprover.java:13)
at com.ldg.GoF23.reponsiabliity.Client.main(Client.java:20)

(2)若将金额修改为1000元,且由校长来处理请求,也会报错,因此需要设置为环状的,也就是最初始的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Client {
public static void main(String[] args) {
// 创建一个请求
PurchaseRequest purchaseRequest = new PurchaseRequest(1, 1000, 1);

// 创建相关的审批人
DepartmentApprover departmentApprover = new DepartmentApprover("张主任");
CollegeApprover collegeApprover = new CollegeApprover("李院长");
ViceSchoolMasterApprover viceSchoolMasterApprover = new ViceSchoolMasterApprover("王副校长");
SchoolMasterApprover schoolMasterApprover = new SchoolMasterApprover("周校长");

// 需要将各个审批级别的下一个设置好(如果没有该审批级别,在最后departmentApprover.processRequest(purchaseRequest) 会直接报空指针异常)
departmentApprover.setApprover(collegeApprover);
collegeApprover.setApprover(viceSchoolMasterApprover);
viceSchoolMasterApprover.setApprover(schoolMasterApprover);
//如果不设置如下代码,则直接使用schoolMasterApprover.processRequest(purchaseRequest) 处理请求时,会报错,因此要成环状
// schoolMasterApprover.setApprover(departmentApprover);
//departmentApprover.processRequest(purchaseRequest);
schoolMasterApprover.processRequest(purchaseRequest);
}
}

结果:

1
2
3
Exception in thread "main" java.lang.NullPointerException
at com.ldg.GoF23.reponsiabliity.SchoolMasterApprover.processRequest(SchoolMasterApprover.java:13)
at com.ldg.GoF23.reponsiabliity.Client.main(Client.java:21)

4、职责链模式在SpringMVC框架应用的源码分析

4.1 代码

1
2
3
4
5
6
7
import org.springframework.web.servlet.DispatcherServlet;

public class ResponsibilityChain {
public static void main(String[] args) {
new DispatcherServlet();
}
}

(1)查看DisPatch类 ctrl+b

(2)查看核心doDispatch

1
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {}

img

(3)查看

1
2
3
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}

1
HandlerInterceptor interceptor = this.interceptorList.get(i);

内部,得到了interceptor对象,并且通过拦截器调用

1
interceptor.preHandle(request, response, this.handler)

img

(4)查看triggerAfterCompletion方法

img

4.2 说明

(1)springmvc请求的流程图中,执行了拦截器相关方法 interceptor.preHandler等等

(2)在处理SpringMvc请求时,使用到职责链模式和适配器模式

(3)HandlerExecutionChain 主要负责的是请求拦截器的执行和请求处理,但是他本身不处理请求,只是将讲求分配给链上注册处理器执行,这是职责链实现方式,减少了职责链本身与处理逻辑之间的耦合,规范了处理流程

(4)HandlerExecutionChain 维护了HandlerInterceptor的集合,可以向其中注册相应的拦截器

5、职责链模式的注意事项和细节

(1)将请求和处理分开,实现解耦,提高系统的灵活性

(2)简化了对象,使对象不需要知道链的结构

(3)性能会收到影响,特别是在链比较长的时候,因此需要控制链中最大节点数量,一般通过在Handler中设置一个最大节点数量,在setNext()方法中判断是否超过阈值,超过则不允许该链简历,避免出现超长链无意识的破坏系统性能

(4)调试不方便,采用了类似递归的方式,调试时逻辑可能比较复杂

(5)最佳应用场景:有多个对象可以处理同一个请求时,比如:多级请求、请假/加薪等审批流程、Java Web中Tomcat对Encoding的处理、拦截器等等

0%