职责链模式

1、OA系统采购审批需求

1)采购员采购教学器材

2)如果金额 小于等于5000,由教学主任审批。(0<=x<=5000)

3)如果金额 小于等于10000,由院长审批。(5000<x<=10000)

4)如果金额 小于等于30000,由副校长审批。(10000<x<=30000)

5)如果金额 超过30000以上,由校长审批。(30000<x)

【传统设计方案】

使用if/else进行判断,不同区间金额调用对应的审批人完成审批。

【传统方式的问题分析】

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

2)传统方式的问题分析:客户端这里会使用到分支判断(比如switch)来对不同的采购请求处理,这样就存在如下问题,一、如果各个级别的人员审批金额发生变化,在客户端的也需要变化。二、客户端必须明确的知道有多少个审批级别和访问。

3)这样对一个采购请求进行处理和Approver(审批人)就存在强耦合关系,不利于代码的扩展和维护。

4)解决方案:职责链模式。


2、策略模式的基本介绍

1)职责链模式(Chain of Responsibility Pattern),又叫责任链模式,为请求创建了一个接收者对象的链,这种模式对请求的发送者和接收者进行解耦。

2)职责链模式通常每个接收者都包含对另一个接收者的引用,如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,以此类推。

3)这种类型的设计模式属于行为型模式。

【职责链模式原理说明】

1)Handler:抽象的处理者,定义了一个处理请求的接口,同时含有另外的Handler(包含抽象处理方法和一个后继连接)。

2)ConcreteHandlerA,B是具体的处理者,处理它自己负责的请求,可以访问它的后继者(即下一个处理者),如果可以处理当前请求则处理,否则就将该请求交给后继者去处理,从而形成一个职责链。

3)Request:含有很多属性,表示一个请求。


3、应用实例代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
public class PurchaseRequest {
private int type = 0; // 请求类型
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;
}

getter
}

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 request);
}

public class DepartmentApprover extends Approver {
public DepartmentApprover(String name) {
super(name);
}

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

public class CollegeApprover extends Approver {
public CollegeApprover(String name) {
super(name);
}

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

public class ViceSchoolMasterApprover extends Approver {
public ViceSchoolMasterApprover(String name) {
super(name);
}

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

public class SchoolMasterApprover extends Approver {
public SchoolMasterApprover(String name) {
super(name);
}

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

public class Client {
public static void main(String[] args) {
// 创建一个请求
PurchaseRequest purchaseRequest = new PurchaseRequest(1, 31000, 1);

// 创建相关的审批人
Approver depart = new DepartmentApprover("张主任");
Approver college = new CollegeApprover("李院长");
Approver viceSchool = new ViceSchoolMasterApprover("马校长");
Approver school =new SchoolMasterApprover("唐校长");

// 需要将各个审批级别的下一个设置好(处理人构成环形)
depart.setApprover(college);
college.setApprover(viceSchool);
viceSchool.setApprover(school);
school.setApprover(depart);

depart.processRequest(purchaseRequest);
}
}

4、职责链模式在SpringMVC框架中应用分析

1)SpringMVC——HandlerExecutionChain类就使用到职责链模式。

2)代码分析

1
2
3
4
5
6
// DispatcherServlet
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) {
HandlerInterceptor拦截调用preHandle方法
HandlerInterceptor拦截调用postHandle方法
HandlerInterceptor拦截调用afterCompletion方法
}
  • SpringMVC请求的流程图中,执行了 拦截器 相关方法,interceptor.preHandler等等。
  • 在处理SpringMVC请求时,使用到职责链模式,还使用到了适配器模式。
  • HandlerExecutionChain主要负责的是请求 拦截器的执行和请求处理,但是它本身不处理请求,只是将请求分配给链上注册处理器执行,这是职责链实现方式,减少职责链本身与处理逻辑之间的耦合,规范了处理流程。
  • HandlerExecutionChain维护了HandlerInterceptor的集合,可以向其中注册相应的拦截器。

3)FilterChain是职责链模式的典型应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// 模拟web请求Request和web响应Response
public interface Request {
}
public interface Response {
}

// 模拟web过滤器Filter
public interface Filter {
public void doFilter(Request req, Response res, FilterChain c);
}

// 模拟实现具体过滤器
public class FirstFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("过滤器1 前置处理");

// 先执行所有request再倒序执行所有reponse
chain.doFilter(request, response);

System.out.println("过滤器1 后置处理");
}
}

// 模拟实现具体过滤器
public class SecondFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("过滤器2 前置处理");

// 先执行所有request再倒序执行所有reponse
chain.doFilter(request, response);

System.out.println("过滤器2 后置处理");
}
}

// 模拟实现过滤器链FilterChain
public class FilterChain {
private List<Filter> filters = new ArrayList<Filter>();
private int index = 0;

// 链式调用
public FilterChain addFilter(Filter filter) {
this.filters.add(filter);
return this;
}

public void doFilter(Request request, Response response) {
if(index == filters.size()) {
return;
}
Filter filter = filters.get(index);
index++;
filter.doFilter(request, response, this);
}
}

// 测试类
public class Client {
public static void main(String[] args) {
Request req = null;
Response res = null;

FilterChain filterChain = new FilterChain();
filterChain.addFilter(new FirstFilter()).addFilter(new SecondFilter());
filterChain.doFilter(req, res);
}
}

5、职责链模式的注意事项及优缺点

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

该模式降低了请求发送者和接收者的耦合度。可以根据需要增加新的请求处理类,满足开闭原则。

当工作流程发生变化,可以动态地改变链内的成员或者修改它们的次序,也可动态地新增或者删除责任。

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

一个对象只需保持一个指向其后继者的引用,不需保持其他所有处理者的引用,这避免了使用众多if、else语句。每个类只需要处理自己该处理的工作,不能处理的传递给下一个对象完成。明确各类的责任范围,符合类的单一职责原则。

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

4)不能保证每个请求一定被处理。由于一个请求没有明确的接收者,所以不能保证它一定会被处理,该请求可能一直传到链的末端都得不到处理。

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

6)职责链建立的合理性要靠客户端来保证,增加了客户端的复杂性,可能会由于职责链的错误设置而导致系统出错,如可能会造成循环调用。

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