老僧长谈设计模式-9-责任链模式

【声明】

本节内容源自网络

【一句话介绍】

当你想要让一个以上的对象有机会能够处理某个请求的时候,就使用责任链模式(Chain of Responsibility Pattern)。

【先混个脸熟】

①类图


  • Handler 抽象处理者角色,定义出一个处理请求的接口。
  • ConcreateHandler 具体处理者角色,具体处理者接到请求后,可以选择将请求处理掉,或者将请求传给下家。

【讲个故事】

著名的红楼梦中-击鼓传花的故事



客户端类

public class DrumBeater 
{
  private static Player player;
  static public void main(String[] args) 
   { 
    player = new JiaMu( new JiaShe( new JiaZheng( new JiaBaoYu(new JiaHuan(null))))); 
    player.handle(4);
   } 
}

抽象类Player

abstract class Player 
{
  abstract public void handle(int i);
  private Player successor; 
  public Player(){
	 successor = null;
  }
   //赋值方法,调用此方法设定下家
   protected void setSuccessor(Player aSuccessor) {
	   successor = aSuccessor;
   }
   
   /**
    * 将花传给下家,如果没有下家,系统停止运行
    * @param index
    */
   public void next(int index){
	  if( successor != null ){
		 successor.handle(index);
	  }else{ 
	    System.out.println("Program terminated.");
	      System.exit(0);
	   }
  }
}


具体类,贾母

class JiaMu extends Player{
	public JiaMu(Player aSuccessor){
		 this.setSuccessor(aSuccessor);
	}
	
	public void handle(int i){
		if( i == 1 ){
			System.out.println("Jia Mu gotta drink!");
		}else{
			System.out.println("Jia Mu passed!"); 
			next(i);
		}
	}
}

具体类,贾宝玉

class JiaBaoYu extends Player{
	public JiaBaoYu(Player aSuccessor){
		this.setSuccessor(aSuccessor);
	}
	
	/*请求处理方法,调用此方法处理请求*/
	public void handle(int i){
		if( i == 4 ){
			System.out.println("Jia Bao Yu gotta drink!");
		}else{
			System.out.println("Jia Bao Yu passed!");
			next(i);
		}
	}
}


【责任链用途】

经常被使用在窗口系统中,处理鼠标和键盘之类的事件。

【责任链优点】

  • 将请求的发送者和接受者解耦。
  • 可以简化你的对象,因为它不需要知道链的结构。
  • 通过改变链内的成员或调动它们的次序,允许你动态地新增或删除责任。

【责任链缺点】

  • 并不保证请求一定会被执行,如果没有任何对象处理它的话,它可能会落到链尾端之外。
  • 可能不容易观察运行时的特征,有碍于除错。

【拓展-应用场景】

常见的应用场景为发票报销和请假流程

这里举一个申请聚餐费用的例子


很多公司都是这样的福利,就是项目组或者是部门可以向公司申请一些聚餐费用,用于组织项目组成员或者是部门成员进行聚餐活动。
申请聚餐费用的大致流程一般是:由申请人先填写申请单,然后交给领导审批,如果申请批准下来,领导会通知申请人审批通过,然后申请人去财务领取费用,如果没有批准下来,领导会通知申请人审批未通过,此事也就此作罢。
不同级别的领导,对于审批的额度是不一样的,比如,项目经理只能审批500元以内的申请;部门经理能审批1000元以内的申请;而总经理可以审核任意额度的申请。
也就是说,当某人提出聚餐费用申请的请求后,该请求会经由项目经理、部门经理、总经理之中的某一位领导来进行相应的处理,但是提出申请的人并不知道最终会由谁来处理他的请求,一般申请人是把自己的申请提交给项目经理,或许最后是由总经理来处理他的请求。


可以使用责任链模式来实现上述功能:当某人提出聚餐费用申请的请求后,该请求会在 项目经理(Project Manager)-->部门经理(Dept Manager)—>总经理 (General Manager)这样一条领导处理链上进行传递,发出请求的人并不知道谁会来处理他的请求,每个领导会根据自己的职责范围,来判断是处理请求还是把请求交给更高级别的领导,只要有领导处理了,传递就结束了。


①类图


②代码

抽象类

public abstract class Handler {  
    /** 
     * 持有下一个处理请求的对象 
     */  
    protected Handler successor = null;  
    /** 
     * 取值方法 
     */  
    public Handler getSuccessor() {  
        return successor;  
    }  
    /** 
     * 设置下一个处理请求的对象 
     */  
    public void setSuccessor(Handler successor) {  
        this.successor = successor;  
    }  
    /** 
     * 处理聚餐费用的申请 
     * @param user    申请人 
     * @param fee    申请的钱数 
     * @return        成功或失败的具体通知 
     */  
    public abstract String handleFeeRequest(String user , double fee);  
}  

具体类-项目经理

public class ProjectManager extends Handler {  
  
    @Override  
    public String handleFeeRequest(String user, double fee) {  
          
        String str = "";  
        //项目经理权限比较小,只能在500以内  
        if(fee < 500)  
        {  
            //为了测试,简单点,只同意张三的请求  
            if("张三".equals(user))  
            {  
                str = "成功:项目经理同意【" + user + "】的聚餐费用,金额为" + fee + "元";      
            }else  
            {  
                //其他人一律不同意  
                str = "失败:项目经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元";  
            }  
        }else  
        {  
            //超过500,继续传递给级别更高的人处理  
            if(getSuccessor() != null)  
            {  
                return getSuccessor().handleFeeRequest(user, fee);  
            }  
        }  
        return str;  
    }  
  
}


部门经理类

public class DeptManager extends Handler {  
  
    @Override  
    public String handleFeeRequest(String user, double fee) {  
          
        String str = "";  
        //部门经理的权限只能在1000以内  
        if(fee < 1000)  
        {  
            //为了测试,简单点,只同意张三的请求  
            if("张三".equals(user))  
            {  
                str = "成功:部门经理同意【" + user + "】的聚餐费用,金额为" + fee + "元";      
            }else  
            {  
                //其他人一律不同意  
                str = "失败:部门经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元";  
            }  
        }else  
        {  
            //超过1000,继续传递给级别更高的人处理  
            if(getSuccessor() != null)  
            {  
                return getSuccessor().handleFeeRequest(user, fee);  
            }  
        }  
        return str;  
    }  
  
} 

总经理类:

public class GeneralManager extends Handler {  
  
    @Override  
    public String handleFeeRequest(String user, double fee) {  
          
        String str = "";  
        //总经理的权限很大,只要请求到了这里,他都可以处理  
        if(fee >= 1000)  
        {  
            //为了测试,简单点,只同意张三的请求  
            if("张三".equals(user))  
            {  
                str = "成功:总经理同意【" + user + "】的聚餐费用,金额为" + fee + "元";      
            }else  
            {  
                //其他人一律不同意  
                str = "失败:总经理不同意【" + user + "】的聚餐费用,金额为" + fee + "元";  
            }  
        }else  
        {  
            //如果还有后继的处理对象,继续传递  
            if(getSuccessor() != null)  
            {  
                return getSuccessor().handleFeeRequest(user, fee);  
            }  
        }  
        return str;  
    }  
  
}

客户端类:



【深挖-责任链模式在Tomcat中的应用】

众所周知Tomcat中的Filter就是使用了责任链模式,创建一个Filter除了要在web.xml文件中做相应配置外,还需要实现javax.servlet.Filter接口。

public class TestFilter implements Filter{

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        
        chain.doFilter(request, response);
    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }

}

使用DEBUG模式所看到的结果如下


其实在真正执行到TestFilter类之前,会经过很多Tomcat内部的类。顺带提一下其实Tomcat的容器设置也是责任链模式,注意被红色方框所圈中的类,从Engine到Host再到Context一直到Wrapper都是通过一个链传递请求。被绿色方框所圈中的地方有一个名为ApplicationFilterChain的类,ApplicationFilterChain类所扮演的就是抽象处理者角色,而具体处理者角色由各个Filter扮演。

第一个疑问是ApplicationFilterChain将所有的Filter存放在哪里?

答案是保存在ApplicationFilterChain类中的一个ApplicationFilterConfig对象的数组中。

/**
 * Filters.
 */
private ApplicationFilterConfig[] filters = 
    new ApplicationFilterConfig[0];

那ApplicationFilterConfig对象又是什么呢?

ApplicationFilterConfig是一个Filter容器。以下是ApplicationFilterConfig类的声明:

/**
 * Implementation of a <code>javax.servlet.FilterConfig</code> useful in
 * managing the filter instances instantiated when a web application
 * is first started.
 *
 * @author Craig R. McClanahan
 * @version $Id: ApplicationFilterConfig.java 1201569 2011-11-14 01:36:07Z kkolinko $
 */

当一个web应用首次启动时ApplicationFilterConfig会自动实例化,它会从该web应用的web.xml文件中读取配置的Filter的信息,然后装进该容器。

刚刚看到在ApplicationFilterChain类中所创建的ApplicationFilterConfig数组长度为零,那它是在什么时候被重新赋值的呢?

是在调用ApplicationFilterChain类的addFilter()方法时。

/**
 * The int which gives the current number of filters in the chain.
 */
private int n = 0;
public static final int INCREMENT = 10;
复制代码
void addFilter(ApplicationFilterConfig filterConfig) {

    // Prevent the same filter being added multiple times
    for(ApplicationFilterConfig filter:filters)
        if(filter==filterConfig)
            return;

    if (n == filters.length) {
        ApplicationFilterConfig[] newFilters =
            new ApplicationFilterConfig[n + INCREMENT];
        System.arraycopy(filters, 0, newFilters, 0, n);
        filters = newFilters;
    }
    filters[n++] = filterConfig;

}

变量n用来记录当前过滤器链里面拥有的过滤器数目,默认情况下n等于0,ApplicationFilterConfig对象数组的长度也等于0,所以当第一次调用addFilter()方法时,if (n == filters.length)的条件成立,ApplicationFilterConfig数组长度被改变。之后filters[n++] = filterConfig;将变量filterConfig放入ApplicationFilterConfig数组中并将当前过滤器链里面拥有的过滤器数目+1。

那ApplicationFilterChain的addFilter()方法又是在什么地方被调用的呢?

是在ApplicationFilterFactory类的createFilterChain()方法中。

1     public ApplicationFilterChain createFilterChain
2         (ServletRequest request, Wrapper wrapper, Servlet servlet) {
3 
4         // get the dispatcher type
5         DispatcherType dispatcher = null; 
6         if (request.getAttribute(DISPATCHER_TYPE_ATTR) != null) {
7             dispatcher = (DispatcherType) request.getAttribute(DISPATCHER_TYPE_ATTR);
8         }
9         String requestPath = null;
10         Object attribute = request.getAttribute(DISPATCHER_REQUEST_PATH_ATTR);
11         
12         if (attribute != null){
13             requestPath = attribute.toString();
14         }
15         
16         // If there is no servlet to execute, return null
17         if (servlet == null)
18             return (null);
19 
20         boolean comet = false;
21         
22         // Create and initialize a filter chain object
23         ApplicationFilterChain filterChain = null;
24         if (request instanceof Request) {
25             Request req = (Request) request;
26             comet = req.isComet();
27             if (Globals.IS_SECURITY_ENABLED) {
28                 // Security: Do not recycle
29                 filterChain = new ApplicationFilterChain();
30                 if (comet) {
31                     req.setFilterChain(filterChain);
32                 }
33             } else {
34                 filterChain = (ApplicationFilterChain) req.getFilterChain();
35                 if (filterChain == null) {
36                     filterChain = new ApplicationFilterChain();
37                     req.setFilterChain(filterChain);
38                 }
39             }
40         } else {
41             // Request dispatcher in use
42             filterChain = new ApplicationFilterChain();
43         }
44 
45         filterChain.setServlet(servlet);
46 
47         filterChain.setSupport
48             (((StandardWrapper)wrapper).getInstanceSupport());
49 
50         // Acquire the filter mappings for this Context
51         StandardContext context = (StandardContext) wrapper.getParent();
52         FilterMap filterMaps[] = context.findFilterMaps();
53 
54         // If there are no filter mappings, we are done
55         if ((filterMaps == null) || (filterMaps.length == 0))
56             return (filterChain);
57 
58         // Acquire the information we will need to match filter mappings
59         String servletName = wrapper.getName();
60 
61         // Add the relevant path-mapped filters to this filter chain
62         for (int i = 0; i < filterMaps.length; i++) {
63             if (!matchDispatcher(filterMaps[i] ,dispatcher)) {
64                 continue;
65             }
66             if (!matchFiltersURL(filterMaps[i], requestPath))
67                 continue;
68             ApplicationFilterConfig filterConfig = (ApplicationFilterConfig)
69                 context.findFilterConfig(filterMaps[i].getFilterName());
70             if (filterConfig == null) {
71                 // FIXME - log configuration problem
72                 continue;
73             }
74             boolean isCometFilter = false;
75             if (comet) {
76                 try {
77                     isCometFilter = filterConfig.getFilter() instanceof CometFilter;
78                 } catch (Exception e) {
79                     // Note: The try catch is there because getFilter has a lot of 
80                     // declared exceptions. However, the filter is allocated much
81                     // earlier
82                     Throwable t = ExceptionUtils.unwrapInvocationTargetException(e);
83                     ExceptionUtils.handleThrowable(t);
84                 }
85                 if (isCometFilter) {
86                     filterChain.addFilter(filterConfig);
87                 }
88             } else {
89                 filterChain.addFilter(filterConfig);
90             }
91         }
92 
93         // Add filters that match on servlet name second
94         for (int i = 0; i < filterMaps.length; i++) {
95             if (!matchDispatcher(filterMaps[i] ,dispatcher)) {
96                 continue;
97             }
98             if (!matchFiltersServlet(filterMaps[i], servletName))
99                 continue;
100             ApplicationFilterConfig filterConfig = (ApplicationFilterConfig)
101                 context.findFilterConfig(filterMaps[i].getFilterName());
102             if (filterConfig == null) {
103                 // FIXME - log configuration problem
104                 continue;
105             }
106             boolean isCometFilter = false;
107             if (comet) {
108                 try {
109                     isCometFilter = filterConfig.getFilter() instanceof CometFilter;
110                 } catch (Exception e) {
111                     // Note: The try catch is there because getFilter has a lot of 
112                     // declared exceptions. However, the filter is allocated much
113                     // earlier
114                 }
115                 if (isCometFilter) {
116                     filterChain.addFilter(filterConfig);
117                 }
118             } else {
119                 filterChain.addFilter(filterConfig);
120             }
121         }
122 
123         // Return the completed filter chain
124         return (filterChain);
125 
126     }

可以将如上代码分为两段,51行之前为第一段,51行之后为第二段。

第一段的主要目的是创建ApplicationFilterChain对象以及一些参数设置。

第二段的主要目的是从上下文中获取所有Filter信息,之后使用for循环遍历并调用filterChain.addFilter(filterConfig);将filterConfig放入ApplicationFilterChain对象的ApplicationFilterConfig数组中。


那ApplicationFilterFactory类的createFilterChain()方法又是在什么地方被调用的呢?

是在StandardWrapperValue类的invoke()方法中被调用的。


由于invoke()方法较长,所以将很多地方省略。

public final void invoke(Request request, Response response)
        throws IOException, ServletException {
   ...省略中间代码
     // Create the filter chain for this request
        ApplicationFilterFactory factory =
            ApplicationFilterFactory.getInstance();
        ApplicationFilterChain filterChain =
            factory.createFilterChain(request, wrapper, servlet);
  ...省略中间代码
         filterChain.doFilter(request.getRequest(), response.getResponse());
  ...省略中间代码
    }

那正常的流程应该是这样的:

在StandardWrapperValue类的invoke()方法中调用ApplicationFilterChai类的createFilterChain()方法———>在ApplicationFilterChai类的createFilterChain()方法中调用ApplicationFilterChain类的addFilter()方法———>在ApplicationFilterChain类的addFilter()方法中给ApplicationFilterConfig数组赋值。


根据上面的代码可以看出StandardWrapperValue类的invoke()方法在执行完createFilterChain()方法后,会继续执行ApplicationFilterChain类的doFilter()方法,然后在doFilter()方法中会调用internalDoFilter()方法。

以下是internalDoFilter()方法的部分代码

//Call the next filter if there is one
if (pos < n) {
//拿到下一个Filter,将指针向下移动一位
    //pos它来标识当前ApplicationFilterChain(当前过滤器链)执行到哪个过滤器
    ApplicationFilterConfig filterConfig = filters[pos++];
    Filter filter = null;
    try {
  //获取当前指向的Filter的实例
        filter = filterConfig.getFilter();
        support.fireInstanceEvent(InstanceEvent.BEFORE_FILTER_EVENT,
                                  filter, request, response);
        
        if (request.isAsyncSupported() && "false".equalsIgnoreCase(
                filterConfig.getFilterDef().getAsyncSupported())) {
            request.setAttribute(Globals.ASYNC_SUPPORTED_ATTR,
                    Boolean.FALSE);
        }
        if( Globals.IS_SECURITY_ENABLED ) {
            final ServletRequest req = request;
            final ServletResponse res = response;
            Principal principal = 
                ((HttpServletRequest) req).getUserPrincipal();

            Object[] args = new Object[]{req, res, this};
            SecurityUtil.doAsPrivilege
                ("doFilter", filter, classType, args, principal);
            
        } else {
    //调用Filter的doFilter()方法  
            filter.doFilter(request, response, this);
        }

这里的filter.doFilter(request, response, this);就是调用我们前面创建的TestFilter中的doFilter()方法。而TestFilter中的doFilter()方法会继续调用chain.doFilter(request, response);方法,而这个chain其实就是ApplicationFilterChain,所以调用过程又回到了上面调用dofilter和调用internalDoFilter方法,这样执行直到里面的过滤器全部执行。

【小结】:

Tomcat中Filter部分的设计是一个典型的责任链模式的应用。

一个有序的责任链表,通过递归调用,变成了一个堆栈执行过程。


【参考】

Java与模式-阎宏

聚餐报销的部分参考:

http://blog.csdn.net/u011225629/article/details/47751697
《Java设计模式 》之责任链模式

Tomcat源码分析部分参考

http://www.cnblogs.com/java-my-life/archive/2012/05/28/2516865.html
《JAVA与模式》之责任链模式


【结束】


1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值