java設計模式-責任鏈模式(Chain of Responsibility)

定義

責任鏈模式是一種對象的行為模式。在責任鏈模式中,很多對象由每一個對象對其下家的引用而連接起來形成一條鏈。請求在這個鏈上傳遞,知道鏈上的某一個對象決定處理此請求,發出這個請求的客戶端并不知道鏈上的哪一個對象最終處理這個請求,這使得系統可以不影響客戶端的情況下動態的重新組織和分配責任。

從擊鼓傳花談起

擊鼓傳花是一種熱鬧而又緊張的飲酒游戲。在酒宴上賓客依次坐定位置,由一個人擊鼓,擊鼓的地方與傳花的地方是分開的,以示公正。開始擊鼓時,花束就開始依次傳遞,鼓聲一落,如果花落在某人手中,則該人就得飲酒。

比如說,賈母、賈赦、賈政、賈寶玉和賈環是五個參加擊鼓傳花游戲的傳花者,他們組成一個環鏈。擊鼓者將花傳給賈母,開始傳花游戲。花由賈母傳給賈赦,由賈赦傳給賈政,由賈政傳給賈寶玉,賈寶玉傳給賈環,賈環再將花傳給賈母,如此往復,如下圖所示。當鼓聲停止時,手中有花的人就得執行酒令。

紅樓夢里的擊鼓傳花

擊鼓傳花是責任鏈模式的應用。責任鏈可能是一條直線、一個環鏈或者一個樹結構的一部分。

責任鏈模式的結構

下面使用了一個責任鏈模式的最簡單的實現。

責任鏈模式的簡單實現

責任鏈模式涉及到的角色如下所示:

  • 抽象處理者角色(Handler):定義出一個處理請求的幾口。如果需要,接口可以定義出一個方法以設定和返回對下家的引用。這個角色通常是由一個Java抽象類或者Java接口實現。上圖中Handler類的聚合關系給出了具體子類對下家的引用,抽象方法handleRequest()規范了子類處理請求的操作。
  • 具體處理者角色(ConcreteHandler):具體處理者接到請求后,可以選擇將請求處理掉,或者將請求傳給下家。由于具體處理者持有對下家的引用,因此,如果需要,具體處理者可以訪問下家。

示例代碼

抽象處理者角色

package com.sschen.handler;

public abstract class Handler {
    /**
     * 持有后繼的責任對象
     */
    protected Handler successor;
    /**
     * 示意處理請求的方法,雖然這個示意方法是么有傳入參數的,但實際
     * 是可以傳入參數的,根據具體需要來選擇是否需要傳遞參數                                            */
    public abstract void handleRequest();
    /**
     * 取值方法
     * @return
     */
    public Handler getSuccessor() {
        return successor;
    }
    /**
     * 賦值方法,指定后繼的責任對象
     * @param successor
     */
    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
}

具體處理者角色

public class ConcreteHandler extends Handler {
    /**
     * 處理方法,調用此方法處理請求
     */
    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;
    /**
     * 取值方法
     * @return
     */
    public Handler getSuccessor() {
        return successor;
    }
    /**
     * 設置下一個處理請求的對象
     * @param successor
     */
    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }
    /**
     * 處理聚餐費用的申請
     * @param user 申請人
     * @param fee 申請金額
     * @return 處理結果,成功或失敗
     */
    public abstract String handlerFeeRequest(String user, double fee);
}

具體處理者角色類

public class ProjectManager extends Handler {
    @Override
    public String handlerFeeRequest(String user, double fee) {
        String str = "";
        if (fee < 500) {//項目經理的權限為500元以下的審批金額
            //為了測試,只同意張三發起的申請請求
            if ("張三".equals(user)) {
                str = "成功:項目經理同意【" + user + "】的聚餐費用申請,金額為【" + fee + "】元";
            } else {
                //其他人一律不同意
                str = "失敗:項目經理不同意【" + user + "】的聚餐費用申請,金額為【" + fee + "】元";
            }
        } else {
            //超過500,繼續傳遞給級別更高的人審批
            if (getSuccessor() != null) {
                return getSuccessor().handlerFeeRequest(user, fee);
            }
        }
        return str;
    }
}
public class DepManager extends Handler {
    @Override
    public String handlerFeeRequest(String user, double fee) {
        String str = "";
        if (fee < 1000) {//部門經理的權限為1000元以下的審批金額
            //為了測試,只同意張三發起的申請請求
            if ("張三".equals(user)) {
                str = "成功:部門經理同意【" + user + "】的聚餐費用申請,金額為【" + fee + "】元";
            } else {
                //其他人一律不同意
                str = "失敗:部門經理不同意【" + user + "】的聚餐費用申請,金額為【" + fee + "】元";
            }
        } else {
            //超過1000,繼續傳遞給級別更高的人審批
            if (getSuccessor() != null) {
                return getSuccessor().handlerFeeRequest(user, fee);
            }
        }
        return str;
    }
}
public class GeneralManager extends Handler {
    @Override
    public String handlerFeeRequest(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().handlerFeeRequest(user, fee);
            }
        }
        return str;
    }
}

客戶端類

public class Client {
    public static void main(String[] args) {
        Handler handler1 = new GeneralManager();
        Handler handler2 = new DepManager();
        Handler handler3 = new ProjectManager();
        handler2.setSuccessor(handler1);
        handler3.setSuccessor(handler2);
        
        String test1 = handler3.handlerFeeRequest("張三", 300);
        System.out.println("test1 = " + test1);
        String test2 = handler3.handlerFeeRequest("李四", 300);
        System.out.println("test2 = " + test2);
        System.out.println("------------------------------------");
        
        String test3 = handler3.handlerFeeRequest("張三", 800);
        System.out.println("test3 = " + test3);
        String test4 = handler3.handlerFeeRequest("李四", 800);
        System.out.println("test4 = " + test4);
        System.out.println("------------------------------------");
        
        String test5 = handler3.handlerFeeRequest("張三", 1500);
        System.out.println("test5 = " + test5);
        String test6 = handler3.handlerFeeRequest("李四", 1500);
        System.out.println("test6 = " + test6);
    }
}

運行結果如下:

test1 = 成功:項目經理同意【張三】的聚餐費用申請,金額為【300.0】元
test2 = 失敗:項目經理不同意【李四】的聚餐費用申請,金額為【300.0】元
------------------------------------
test3 = 成功:部門經理同意【張三】的聚餐費用申請,金額為【800.0】元
test4 = 失敗:部門經理不同意【李四】的聚餐費用申請,金額為【800.0】元
------------------------------------
test5 = 成功:總經理同意【張三】的聚餐費用申請,金額為【1500.0】元
test6 = 失敗:總經理不同意【李四】的聚餐費用申請,金額為【1500.0】元

純與不純的責任鏈模式

一個純的責任鏈模式要求一個具體的處理者對象只能在兩個行為中選擇一個:一是承擔責任,二是將責任推給下家。不允許出現某一個具體處理者對象在承擔了一部分責任后,又把責任向下傳遞的情況。

在一個純的責任鏈模式里面,一個請求必須被某一個處理者對象所接收;在一個不純的責任鏈模式里面,一個請求可以最終不被任何接收端對象所接收。

純的責任鏈模式的實際例子很難找到,一般看到的例子均是不純的責任鏈模式的實現。有些人認為不純的責任鏈根本不是責任鏈模式,這也許是有道理的。但是在實際的系統中,純的責任鏈模式很難找到。如果堅持責任鏈不純就不是責任鏈模式,那么責任鏈模式便不會有太大意義了。

責任鏈模式在Tomcat中的應用

眾所周知,Tomcat中的Filter就是使用了責任鏈模式,創建一個Filter除了要在web.xml文件中做相應配置外,還需要實現javax.servlet.Filter接口。

public class TestFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
    }
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}

使用Debug模式所看到的結果如下:

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數組長度為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

那么ApplicationFileterChain的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()方法中被調用的。

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()方法中調用ApplicationFilterChain類中createFilterChain()方法 -->
ApplicationFilterChain類的createFilterChain()方法中調用ApplicationFilterChain類的addFilter()方法 -->
ApplicationFilterChain類的addFilter()方法中給ApplicationFilterConfig數組賦值。

Filter調用流程

根據上面的代碼可以看出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, reponse, this);就是調用我們之前創建的TestFilter中的doFilter()方法。而TestFilter中的doFilter()方法會繼續調用chain.doFilter(request, response);方法,而這個chain其實就是ApplicationFilterChain,所以調用過程又回調了上面調用doFilter和調用internalDoFilter方法,這樣執行直到里面的過濾器全部執行。

如果定義兩個過濾器,則Debug結果如下:

多個過濾器執行結果

參考

《JAVA與模式》之責任鏈模式

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容