What

Chain of Responsibility is a design pattern to pass responsibility to other objects in a chain. This simple definition is a little bit confusing, in other words, sometimes you send a message to one object, that object can’t handle, so the object ask another object to help, usually with same type. And the responsibility can pass one by one recursively. It looks very similar with a linked list, one node can have a next pointer which point to another node, until the next pointer is null.


When

In objected-oreinted programming, usually we send one message to one object when we need it to do specific task for us. But sometimes we may need more than one object to do that task, and we need a flexible dispatch strategy to assign different objects to handle that. Chain of responsibility is a good pattern to achieve this requirements. It puts all objects involved inside a pipeline, the client just need to launch at the head of the pipiline, all the processing will be done recursively.

How


(From https://sourcemaking.com/design_patterns/chain_of_responsibility)

The structure of chain of responsibility is also similar with a linked list. In Handler there is a pointer nextHandler which is point to another Hanlder object. Once the pipiline is launched at the entrance, the node will check if itself can handle the request, otherwise, it will pass the responsibility to nextHandler, and so on.

Where

Fisrt thing comes to my mind about chain of responsibility is the Rack middleware in Ruby world. In a Rack application, you can use any middleware in the front of your application, all the middlewares are chained together, and will be called one by one when request comes.

In Java world, there is something like Rack middleware, the servlet filter. A filter can do some work on the http request, such as authentication, authorization or logging. You need to implement the Filter interface if you want to define your own filter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import javax.servlet.*;
import java.io.IOException;

public class ExampleFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}

public void doFilter(ServletRequest servletRequest,
ServletResponse servletResponse,
FilterChain filterChain)
throws IOException, ServletException {
// do the filter process
filterChain.doFilter(servletRequest, servletResponse);
}

public void destroy() {
}
}

Above is a scaffold for Filter implementation, this line filterChain.doFilter(servletRequest, servletResponse) is the filter forward the request and response to next filter after the filter processing finished. That’s the point where chain of responsibility pattern happens.