Friday, September 11, 2015

Chain of Responsibility Pattern



https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series ofprocessing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.
the chain of responsibility pattern creates a chain of receiver objects for a request. This pattern decouples sender and receiver of a request based on type of request. 
In this pattern, normally each receiver contains reference to another receiver. If one object cannot handle the request then it passes the same to the next receiver and so on.

https://sourcemaking.com/design_patterns/chain_of_responsibility
Intent
  • Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
  • Launch-and-leave requests with a single processing pipeline that contains many possible handlers.
  • An object-oriented linked list with recursive traversal.
The pattern chains the receiving objects together, and then passes any request messages from object to object until it reaches an object capable of handling the message. The number and type of handler objects isn't known a priori, they can be configured dynamically. The chaining mechanism uses recursive composition to allow an unlimited number of handlers to be linked.
Chain of Responsibility simplifies object interconnections. Instead of senders and receivers maintaining references to all candidate receivers, each sender keeps a single reference to the head of the chain, and each receiver keeps a single reference to its immediate successor in the chain.
Make sure there exists a "safety net" to "catch" any requests which go unhandled.
Do not use Chain of Responsibility when each request is only handled by one handler, or, when the client object knows which service object should handle the request.

  • Handler   (Approver)
    • defines an interface for handling the requests
    • (optional) implements the successor link
  • ConcreteHandler   (Director, VicePresident, President)
    • handles requests it is responsible for
    • can access its successor
    • if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor
  • Client   (ChainApp)
    • initiates the request to a ConcreteHandler object on the chain
http://www.sitepoint.com/introduction-to-chain-of-responsibility/
A Service Container (or dependency injection container) that manages the instantiation of objects without creating them each time helps improve memory and performance.

If CoR receives the same type of request often, a caching system is useful for improving speed. Examples
https://en.wikipedia.org/wiki/Chain-of-responsibility_pattern
PurchasePower
ManagerPPower
DirectorPPower
VicePresidentPPower
PresidentPPower
PurchaseRequest
abstract class PurchasePower {
    protected static final double BASE = 500;
    protected PurchasePower successor;

    public void setSuccessor(PurchasePower successor) {
        this.successor = successor;
    }

    abstract public void processRequest(PurchaseRequest request);
}
Four implementations of the abstract class above: Manager, Director, Vice President, President
class ManagerPPower extends PurchasePower {
    private final double ALLOWABLE = 10 * BASE;

    public void processRequest(PurchaseRequest request) {
        if (request.getAmount() < ALLOWABLE) {
            System.out.println("Manager will approve $" + request.getAmount());
        } else if (successor != null) {
            successor.processRequest(request);
        }
    }
}

class DirectorPPower extends PurchasePower {
    private final double ALLOWABLE = 20 * BASE;

    public void processRequest(PurchaseRequest request) {
        if (request.getAmount() < ALLOWABLE) {
            System.out.println("Director will approve $" + request.getAmount());
        } else if (successor != null) {
            successor.processRequest(request);
        }
    }
}
class PurchaseRequest {
    private double amount;
    private String purpose;

    public PurchaseRequest(double amount, String purpose) {
        this.amount = amount;
        this.purpose = purpose;
    }
}

        ManagerPPower manager = new ManagerPPower();
        DirectorPPower director = new DirectorPPower();
        VicePresidentPPower vp = new VicePresidentPPower();
        PresidentPPower president = new PresidentPPower();
        manager.setSuccessor(director);
        director.setSuccessor(vp);
        vp.setSuccessor(president);
       manager.processRequest(new PurchaseRequest(d, "General"))

In JDK

In JavaEE, the concept of Servlet filters implement the Chain of Responsibility pattern, and may also decorate the request to add extra information before the request is handled by a servlet.
http://bylijinnan.iteye.com/blog/1981761
Intercepting Filter类似于职责链模式 
有两种实现 
其中一种是Filter之间没有联系,全部Filter都存放在FilterChain中,由FilterChain来有序或无序地把把所有Filter调用一遍。没有用到链表这种数据结构.

另一种是一个Filter“持有”下一个Filter,下一个Filter的调用由上一个Filter决定。这其中就用到了链表这种数据结构。 

When to Use
http://www.oodesign.com/chain-of-responsibility-pattern.html
  • More than one object can handle a command
  • The handler is not known in advance
  • The handler should be determined automatically
  • It’s wished that the request is addressed to a group of objects without explicitly specifying its receiver
  • The group of objects that may handle the command must be specified in a dynamic way

Need to make sure
The chain is not broken and command should be handled.
  • The fundamental flaw of the pattern is the fact that it gets easily broken: if the programmer forgets to call the next handler in the concreteHandler the request gets lost on the way. This problem comes from the fact that the execution is not handled entirely by the superclass and the call is triggered in the superclass.
  • When implementing the CoR pattern a special care should be taken for the request representation. The request is not considered a distinctive part of the CoR pattern, but it is still used in all the components of the pattern.
  • Another flaw of the Chain of Responsibility is the fact that some requests may end up unhandled due to the wrong implementation of concrete handler, their propagation slowing down the rest of the application. This means that extra care is needed when taking into account the requests that may appear in the process.
https://dzone.com/articles/design-patterns-uncovered-chain-of-responsibility
Chain of Responsibility can make it difficult to follow through the logic of a particular path in the code at runtime. It's also important to note that there is the potential that the request could reach the end of the chain and not be handled at all.

CoR promotes loose coupling: every handler could be changed (or removed) without a big impact on the whole structure, but its flexibility, with a wrong design, can cause problems on all the chain’s objects involved.
  • Chain of Responsibility can use Command to represent requests as objects.
在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。

  责任链模式涉及到的角色如下所示:
  ●  抽象处理者(Handler)角色:定义出一个处理请求的接口。如果需要,接口可以定义 出一个方法以设定和返回对下家的引用。这个角色通常由一个Java抽象类或者Java接口实现。上图中Handler类的聚合关系给出了具体子类对下家的引用,抽象方法handleRequest()规范了子类处理请求的操作。
  ●  具体处理者(ConcreteHandler)角色:具体处理者接到请求后,可以选择将请求处理掉,或者将请求传给下家。由于具体处理者持有对下家的引用,因此,如果需要,具体处理者可以访问下家。
  可以使用责任链模式来实现上述功能:当某人提出聚餐费用申请的请求后,该请求会在 项目经理—〉部门经理—〉总经理 这样一条领导处理链上进行传递,发出请求的人并不知道谁会来处理他的请求,每个领导会根据自己的职责范围,来判断是处理请求还是把请求交给更高级别的领导,只要有领导处理了,传递就结束了。
  需要把每位领导的处理独立出来,实现成单独的职责处理对象,然后为它们提供一个公共的、抽象的父职责对象,这样就可以在客户端来动态地组合职责链,实现不同的功能要求了。

纯的与不纯的责任链模式

  一个纯的责任链模式要求一个具体的处理者对象只能在两个行为中选择一个:一是承担责任,而是把责任推给下家。不允许出现某一个具体处理者对象在承担了一部分责任后又 把责任向下传的情况。
  在一个纯的责任链模式里面,一个请求必须被某一个处理者对象所接收;在一个不纯的责任链模式里面,一个请求可以最终不被任何接收端对象所接收。
  纯的责任链模式的实际例子很难找到,一般看到的例子均是不纯的责任链模式的实现。有些人认为不纯的责任链根本不是责任链模式,这也许是有道理的。但是在实际的系统里,纯的责任链很难找到。如果坚持责任链不纯便不是责任链模式,那么责任链模式便不会有太大意义了。

  其实在真正执行到TestFilter类之前,会经过很多Tomcat内部的类。顺带提一下其实Tomcat的容器设置也是责任链模式,注意被红色方框所圈中的类,从Engine到Host再到Context一直到Wrapper都是通过一个链传递请求。被绿色方框所圈中的地方有一个名为ApplicationFilterChain的类,ApplicationFilterChain类所扮演的就是抽象处理者角色,而具体处理者角色由各个Filter扮演。
  第一个疑问是ApplicationFilterChain将所有的Filter存放在哪里?
  答案是保存在ApplicationFilterChain类中的一个ApplicationFilterConfig对象的数组中。
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.
  当一个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()方法中。
  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方法,这样执行直到里面的过滤器全部执行。
  如果定义两个过滤器,则Debug结果如下:

Labels

Review (572) System Design (334) System Design - Review (198) Java (189) Coding (75) Interview-System Design (65) Interview (63) Book Notes (59) Coding - Review (59) to-do (45) Linux (43) Knowledge (39) Interview-Java (35) Knowledge - Review (32) Database (31) Design Patterns (31) Big Data (29) Product Architecture (28) MultiThread (27) Soft Skills (27) Concurrency (26) Cracking Code Interview (26) Miscs (25) Distributed (24) OOD Design (24) Google (23) Career (22) Interview - Review (21) Java - Code (21) Operating System (21) Interview Q&A (20) System Design - Practice (20) Tips (19) Algorithm (17) Company - Facebook (17) Security (17) How to Ace Interview (16) Brain Teaser (14) Linux - Shell (14) Redis (14) Testing (14) Tools (14) Code Quality (13) Search (13) Spark (13) Spring (13) Company - LinkedIn (12) How to (12) Interview-Database (12) Interview-Operating System (12) Solr (12) Architecture Principles (11) Resource (10) Amazon (9) Cache (9) Git (9) Interview - MultiThread (9) Scalability (9) Trouble Shooting (9) Web Dev (9) Architecture Model (8) Better Programmer (8) Cassandra (8) Company - Uber (8) Java67 (8) Math (8) OO Design principles (8) SOLID (8) Design (7) Interview Corner (7) JVM (7) Java Basics (7) Kafka (7) Mac (7) Machine Learning (7) NoSQL (7) C++ (6) Chrome (6) File System (6) Highscalability (6) How to Better (6) Network (6) Restful (6) CareerCup (5) Code Review (5) Hash (5) How to Interview (5) JDK Source Code (5) JavaScript (5) Leetcode (5) Must Known (5) Python (5)

Popular Posts