当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA设计模式之责任链模式详解

JAVA设计模式之责任链模式详解

2019年07月22日  | 移动技术网IT编程  | 我要评论

在阎宏博士的《java与模式》一书中开头是这样描述责任链(chain of responsibility)模式的:

  责任链模式是一种对象的行为模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。

从击鼓传花谈起

  击鼓传花是一种热闹而又紧张的饮酒游戏。在酒宴上宾客依次坐定位置,由一人击鼓,击鼓的地方与传花的地方是分开的,以示公正。开始击鼓时,花束就开始依次传递,鼓声一落,如果花束在某人手中,则该人就得饮酒。

  比如说,贾母、贾赦、贾政、贾宝玉和贾环是五个参加击鼓传花游戏的传花者,他们组成一个环链。击鼓者将花传给贾母,开始传花游戏。花由贾母传给贾赦,由贾赦传给贾政,由贾政传给贾宝玉,又贾宝玉传给贾环,由贾环传回给贾母,如此往复,如下图所示。当鼓声停止时,手中有花的人就得执行酒令。

  击鼓传花便是责任链模式的应用。责任链可能是一条直线、一个环链或者一个树结构的一部分。

责任链模式的结构

  下面使用了一个责任链模式的最简单的实现。

责任链模式涉及到的角色如下所示:

  ●  抽象处理者(handler)角色:定义出一个处理请求的接口。如果需要,接口可以定义 出一个方法以设定和返回对下家的引用。这个角色通常由一个java抽象类或者java接口实现。上图中handler类的聚合关系给出了具体子类对下家的引用,抽象方法handlerequest()规范了子类处理请求的操作。
  ●  具体处理者(concretehandler)角色:具体处理者接到请求后,可以选择将请求处理掉,或者将请求传给下家。由于具体处理者持有对下家的引用,因此,如果需要,具体处理者可以访问下家。

源代码

  抽象处理者角色

复制代码 代码如下:

public abstract class handler {
   
    /**
     * 持有后继的责任对象
     */
    protected handler successor;
    /**
     * 示意处理请求的方法,虽然这个示意方法是没有传入参数的
     * 但实际是可以传入参数的,根据具体需要来选择是否传递参数
     */
    public abstract void handlerequest();
    /**
     * 取值方法
     */
    public handler getsuccessor() {
        return successor;
    }
    /**
     * 赋值方法,设置后继的责任对象
     */
    public void setsuccessor(handler successor) {
        this.successor = successor;
    }
   
}

具体处理者角色

复制代码 代码如下:

public class concretehandler extends handler {
    /**
     * 处理方法,调用此方法处理请求
     */
    @override
    public void handlerequest() {
        /**
         * 判断是否有后继的责任对象
         * 如果有,就转发请求给后继的责任对象
         * 如果没有,则处理请求
         */
        if(getsuccessor() != null)
        {           
            system.out.println("放过请求");
            getsuccessor().handlerequest();           
        }else
        {           
            system.out.println("处理请求");
        }
    }

}


客户端类
复制代码 代码如下:

public class client {

    public static void main(string[] args) {
        //组装责任链
        handler handler1 = new concretehandler();
        handler handler2 = new concretehandler();
        handler1.setsuccessor(handler2);
        //提交请求
        handler1.handlerequest();
    }

}

  可以看出,客户端创建了两个处理者对象,并指定第一个处理者对象的下家是第二个处理者对象,而第二个处理者对象没有下家。然后客户端将请求传递给第一个处理者对象。

  由于本示例的传递逻辑非常简单:只要有下家,就传给下家处理;如果没有下家,就自行处理。因此,第一个处理者对象接到请求后,会将请求传递给第二个处理者对象。由于第二个处理者对象没有下家,于是自行处理请求。活动时序图如下所示。

使用场景

  来考虑这样一个功能:申请聚餐费用的管理。

  很多公司都是这样的福利,就是项目组或者是部门可以向公司申请一些聚餐费用,用于组织项目组成员或者是部门成员进行聚餐活动。

  申请聚餐费用的大致流程一般是:由申请人先填写申请单,然后交给领导审批,如果申请批准下来,领导会通知申请人审批通过,然后申请人去财务领取费用,如果没有批准下来,领导会通知申请人审批未通过,此事也就此作罢。

  不同级别的领导,对于审批的额度是不一样的,比如,项目经理只能审批500元以内的申请;部门经理能审批1000元以内的申请;而总经理可以审核任意额度的申请。

  也就是说,当某人提出聚餐费用申请的请求后,该请求会经由项目经理、部门经理、总经理之中的某一位领导来进行相应的处理,但是提出申请的人并不知道最终会由谁来处理他的请求,一般申请人是把自己的申请提交给项目经理,或许最后是由总经理来处理他的请求。

  

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

  需要把每位领导的处理独立出来,实现成单独的职责处理对象,然后为它们提供一个公共的、抽象的父职责对象,这样就可以在客户端来动态地组合职责链,实现不同的功能要求了。

源代码

  抽象处理者角色类

复制代码 代码如下:

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

}

客户端类

复制代码 代码如下:

public class client {

    public static void main(string[] args) {
        //先要组装责任链
        handler h1 = new generalmanager();
        handler h2 = new deptmanager();
        handler h3 = new projectmanager();
        h3.setsuccessor(h2);
        h2.setsuccessor(h1);
       
        //开始测试
        string test1 = h3.handlefeerequest("张三", 300);
        system.out.println("test1 = " + test1);
        string test2 = h3.handlefeerequest("李四", 300);
        system.out.println("test2 = " + test2);
        system.out.println("---------------------------------------");
       
        string test3 = h3.handlefeerequest("张三", 700);
        system.out.println("test3 = " + test3);
        string test4 = h3.handlefeerequest("李四", 700);
        system.out.println("test4 = " + test4);
        system.out.println("---------------------------------------");
       
        string test5 = h3.handlefeerequest("张三", 1500);
        system.out.println("test5 = " + test5);
        string test6 = h3.handlefeerequest("李四", 1500);
        system.out.println("test6 = " + test6);
    }

}


运行结果如下所示:

纯的与不纯的责任链模式

  一个纯的责任链模式要求一个具体的处理者对象只能在两个行为中选择一个:一是承担责任,而是把责任推给下家。不允许出现某一个具体处理者对象在承担了一部分责任后又 把责任向下传的情况。

  在一个纯的责任链模式里面,一个请求必须被某一个处理者对象所接收;在一个不纯的责任链模式里面,一个请求可以最终不被任何接收端对象所接收。

  纯的责任链模式的实际例子很难找到,一般看到的例子均是不纯的责任链模式的实现。有些人认为不纯的责任链根本不是责任链模式,这也许是有道理的。但是在实际的系统里,纯的责任链很难找到。如果坚持责任链不纯便不是责任链模式,那么责任链模式便不会有太大意义了。

责任链模式在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数组长度为零,那它是在什么时候被重新赋值的呢?

复制代码 代码如下:

private applicationfilterconfig[] filters =
        new applicationfilterconfig[0];

是在调用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()方法中。

复制代码 代码如下:

public applicationfilterchain createfilterchain
        (servletrequest request, wrapper wrapper, servlet servlet) {

        // get the dispatcher type
        dispatchertype dispatcher = null;
        if (request.getattribute(dispatcher_type_attr) != null) {
            dispatcher = (dispatchertype) request.getattribute(dispatcher_type_attr);
        }
        string requestpath = null;
        object attribute = request.getattribute(dispatcher_request_path_attr);
       
        if (attribute != null){
            requestpath = attribute.tostring();
        }
       
        // if there is no servlet to execute, return null
        if (servlet == null)
            return (null);

        boolean comet = false;
       
        // create and initialize a filter chain object
        applicationfilterchain filterchain = null;
        if (request instanceof request) {
            request req = (request) request;
            comet = req.iscomet();
            if (globals.is_security_enabled) {
                // security: do not recycle
                filterchain = new applicationfilterchain();
                if (comet) {
                    req.setfilterchain(filterchain);
                }
            } else {
                filterchain = (applicationfilterchain) req.getfilterchain();
                if (filterchain == null) {
                    filterchain = new applicationfilterchain();
                    req.setfilterchain(filterchain);
                }
            }
        } else {
            // request dispatcher in use
            filterchain = new applicationfilterchain();
        }

        filterchain.setservlet(servlet);

        filterchain.setsupport
            (((standardwrapper)wrapper).getinstancesupport());

        // acquire the filter mappings for this context
        standardcontext context = (standardcontext) wrapper.getparent();
        filtermap filtermaps[] = context.findfiltermaps();

        // if there are no filter mappings, we are done
        if ((filtermaps == null) || (filtermaps.length == 0))
            return (filterchain);

        // acquire the information we will need to match filter mappings
        string servletname = wrapper.getname();

        // add the relevant path-mapped filters to this filter chain
        for (int i = 0; i < filtermaps.length; i++) {
            if (!matchdispatcher(filtermaps[i] ,dispatcher)) {
                continue;
            }
            if (!matchfiltersurl(filtermaps[i], requestpath))
                continue;
            applicationfilterconfig filterconfig = (applicationfilterconfig)
                context.findfilterconfig(filtermaps[i].getfiltername());
            if (filterconfig == null) {
                // fixme - log configuration problem
                continue;
            }
            boolean iscometfilter = false;
            if (comet) {
                try {
                    iscometfilter = filterconfig.getfilter() instanceof cometfilter;
                } catch (exception e) {
                    // note: the try catch is there because getfilter has a lot of
                    // declared exceptions. however, the filter is allocated much
                    // earlier
                    throwable t = exceptionutils.unwrapinvocationtargetexception(e);
                    exceptionutils.handlethrowable(t);
                }
                if (iscometfilter) {
                    filterchain.addfilter(filterconfig);
                }
            } else {
                filterchain.addfilter(filterconfig);
            }
        }

        // add filters that match on servlet name second
        for (int i = 0; i < filtermaps.length; i++) {
            if (!matchdispatcher(filtermaps[i] ,dispatcher)) {
                continue;
            }
            if (!matchfiltersservlet(filtermaps[i], servletname))
                continue;
            applicationfilterconfig filterconfig = (applicationfilterconfig)
                context.findfilterconfig(filtermaps[i].getfiltername());
            if (filterconfig == null) {
                // fixme - log configuration problem
                continue;
            }
            boolean iscometfilter = false;
            if (comet) {
                try {
                    iscometfilter = filterconfig.getfilter() instanceof cometfilter;
                } catch (exception e) {
                    // note: the try catch is there because getfilter has a lot of
                    // declared exceptions. however, the filter is allocated much
                    // earlier
                }
                if (iscometfilter) {
                    filterchain.addfilter(filterconfig);
                }
            } else {
                filterchain.addfilter(filterconfig);
            }
        }

        // return the completed filter chain
        return (filterchain);

    }

可以将如上代码分为两段,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方法,这样执行直到里面的过滤器全部执行。

  如果定义两个过滤器,则debug结果如下:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网