职责链模式

问题

1
2
3
4
5
6
学校OA系统的采购审批项目:需求是
1)采购员采购教学器材
2)如果金额小于等于5000,由教学主任审批
3)如果金额小于等于10000,由院长审批
4)如果金额小于等于30000,由副校长审批
5)如果金额超过30000以上,有校长审批请设计程序完成采购审批项目

传统方案解决oA系统审批问题

  • 传统方式是:接收到一个采购请求后,根据采购金额来调用对应的Approver (审批人)完成审批。
  • 传统方式的问题分析:客户端这里会使用到分支判断(比如switch)来对不同的采购请求处理,这样就存在如下问题
    1. 如果各个级别的人员审批金额发生变化,在客户端的也需要变化
    2. 客户端必须明确的知道有多少个审批级别和访问
  • 这样对一个采购请求进行处理和Approver(审批人)就存在强耦合关系,不利于代码的扩展和维护

基本介绍

  • 职责链模式( Chain ofResponsibility iattern) ,又叫责任链模式,为请求创建了一个接收者对象的链。这种模式对请求的发送者和接收者进行解耦。
  • 职责链模式通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
    这种类型的设计模式属于行为型模式
责任链模式的结构图
  • Handler :抽象的处理者,定义了一个处理请求的接口,同时含义另外Handler
  • ConcreteHandlerA , B是具体的处理者,处理它自己负责的请求,可以访问它的后继者(即下一个处理者),如果可以处理当前请求,则处理,否则就将该请求交个后继者去处理,从而形成一个职责链
  • Request ,含义很多属性,表示一个请求
责任链

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

解决问题

  1. 请求类,这个类是一个请求类,用于在责任链中传递。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    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;
    }

    public int getType() {
    return type;
    }

    public float getPrice() {
    return price;
    }

    public int getId() {
    return id;
    }
    }
  2. 责任链抽象类

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

    Approve approve; //下一个处理者
    String name; //名字

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

    public void setApprove(Approve approve) {
    this.approve = approve;
    }

    //处理审批的方法,得到一个请求,处理是子类完成
    public abstract void processRequest(PurchaseRequest purchaseRequest);
    }
    1. 主任类

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

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

      @Override
      public void processRequest(PurchaseRequest purchaseRequest) {
      if (purchaseRequest.getPrice() <= 5000){
      System.out.println("请求编号 id=" +
      purchaseRequest.getId()+ " 被 "+this.name + "处理");
      }else{
      //其他人处理
      approve.processRequest(purchaseRequest);
      }
      }
      }
    2. 院长类

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

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

      @Override
      public void processRequest(PurchaseRequest purchaseRequest) {
      if (purchaseRequest.getPrice() <= 10000){
      System.out.println("请求编号 id=" +
      purchaseRequest.getId()+ " 被 "+this.name + "处理");
      }else{
      //其他人处理
      approve.processRequest(purchaseRequest);
      }
      }
      }
  3. 客户端调用

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    public class Client {
    public static void main(String[] args) {

    //请求
    PurchaseRequest purchaseRequest = new PurchaseRequest(1, 10000, 1);

    //创建相关审批人
    DepartmentApprove departmentApprove = new DepartmentApprove("主任");
    CollegeApprove collegeApprove = new CollegeApprove("院长");

    //设置,构成环状
    departmentApprove.setApprove(collegeApprove);
    collegeApprove.setApprove(departmentApprove);


    departmentApprove.processRequest(purchaseRequest);
    }
    }

源码

SpringMVC

HandlerExecutionChain

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
@SuppressWarnings("serial")
public class DispatcherServlet extends FrameworkServlet {

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpServletRequest processedRequest = request;
//1.
HandlerExecutionChain mappedHandler = null;
boolean multipartRequestParsed = false;

WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);

try {
ModelAndView mv = null;
Exception dispatchException = null;

try {
processedRequest = checkMultipart(request);
multipartRequestParsed = (processedRequest != request);

// Determine handler for the current request.
//2.拿到过滤器链
mappedHandler = getHandler(processedRequest);
if (mappedHandler == null || mappedHandler.getHandler() == null) {
noHandlerFound(processedRequest, response);
return;
}

...
//3.调用过滤器链的PreHandle,如果调用成功就直接return
if (!mappedHandler.applyPreHandle(processedRequest, response)) {
return;
}

// Actually invoke the handler.
mv = ha.handle(processedRequest, response, mappedHandler.getHandler());

if (asyncManager.isConcurrentHandlingStarted()) {
return;
}

applyDefaultViewName(processedRequest, mv);
//4.调用postHandle
mappedHandler.applyPostHandle(processedRequest, response, mv);
}
catch (Exception ex) {
dispatchException = ex;
}
catch (Throwable err) {
// As of 4.3, we're processing Errors thrown from handler methods as well,
// making them available for @ExceptionHandler methods and other scenarios.
dispatchException = new NestedServletException("Handler dispatch failed", err);
}
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
}
catch (Exception ex) {
triggerAfterCompletion(processedRequest, response, mappedHandler, ex);
}
catch (Throwable err) {
triggerAfterCompletion(processedRequest, response, mappedHandler,
new NestedServletException("Handler processing failed", err));
}
finally {
if (asyncManager.isConcurrentHandlingStarted()) {
// Instead of postHandle and afterCompletion
if (mappedHandler != null) {
mappedHandler.applyAfterConcurrentHandlingStarted(processedRequest, response);
}
}
else {
// Clean up any resources used by a multipart request.
if (multipartRequestParsed) {
cleanupMultipart(processedRequest);
}
}
}
}
}
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
public class HandlerExecutionChain {

//调用拦截器的preHandle
boolean applyPreHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = 0; i < interceptors.length; i++) {
//获取拦截器
HandlerInterceptor interceptor = interceptors[i];
//调用拦截器的preHandle方法
if (!interceptor.preHandle(request, response, this.handler)) {
//调用After
triggerAfterCompletion(request, response, null);
return false;
}
this.interceptorIndex = i;
}
}
return true;
}

//调用拦截器的postHandle
void applyPostHandle(HttpServletRequest request, HttpServletResponse response, ModelAndView mv) throws Exception {
HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = interceptors.length - 1; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
interceptor.postHandle(request, response, this.handler, mv);
}
}
}

//调用
void triggerAfterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex)
throws Exception {

HandlerInterceptor[] interceptors = getInterceptors();
if (!ObjectUtils.isEmpty(interceptors)) {
for (int i = this.interceptorIndex; i >= 0; i--) {
HandlerInterceptor interceptor = interceptors[i];
try {
interceptor.afterCompletion(request, response, this.handler, ex);
}
catch (Throwable ex2) {
logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
}
}
}
}
}
  • Springmvc 请求的流程图中,执行了拦截器相关方法interceptor.preHandler等等在处理
  • SpringMvc请求时,使用到职责链模式还使用到适配器模式
  • HandlerExecutionChain主要负责的是请求拦截器的执行和请求处理,但是他本身不处理请求,只是将请求分配给链上注册处理器执行,这是职责链实现方式,减少职责链本身与处理逻辑之间的耦合,规范了处理流程
  • HandlerExecutionChain维护了HandlerInterceptor的集合,可以向其中注册相应的拦截器.

注意事项

  • 将请求和处理分开,实现解耦,提高系统的灵活性
  • 简化了对象,使对象不需要知道链的结构
  • 性能会受到影响,特别是在链比较长的时候,因此需控制链中最大节点数量,一般通过在Handler中设置一个最大节点数量,在setNext()方法中判断是否已经超过阀值,超过则不允许该链建立,避免出现超长链无意识地破坏系统性能
  • 调试不方便。采用了类似递归的方式,调试时逻辑可能比较复杂
  • 最佳应用场景:有多个对象可以处理同一个请求时,比如:多级请求、请假/加薪等审批流程、Java Web中Tomcat对Encoding的处理、拦截器