Introduction to: Patterns of Design (I)

The purpose of this post is to try to introduce the Patterns of Design. In this first chapter the Chain of Responsibility will be introduced.

First of all, let’s see the UML class diagram for this pattern:

UML class diagram for the Chain of Responsability Pattern

The purpose of this pattern is giving more than one object the opportunity to handle an event or request. The pattern consists of one abstract class named Handler. This class has a method named HandleRequest, and has an self-relationship called successor. Its goal is to create a chain, so each link has the possibility to handle the request. As you can see in the diagram, the client only “has to know” about the Handler. The only but, it’s that someone has to create the Chain with all its links (each ConcreteHandler). A XML file can be used for this purpose, another possibility is to hard-code the creation of the entire chain.

When a Client calls the HandleRequest on Handler, it’s processed by one ConcreteHandler, which has to decide if the request has to be processed or not. Once processed, it has to decide if the request has to be processed by the next link or otherwise finish the processing.

Filters in Web Applications (which will be introduced in a future post) are an actual example of this pattern. The web.xml is the file that models the chain, in this file it’s stated which classes will set up each link of the chain. In web filters, each HttpRequest it’s processed by the first link (filter), and it has to decide if the request will be processed by the next filter. The order of processing and calling the next link can be reversed, so first of all the link calls the next link in chain and then it will process the request after the callback.

Another real example where I used this pattern: we had to process a document and decide where to deliver it. We knew that more destinations would be added in a future, but we didn’t know the algorithm for the unknown destinations. So we decided to implement a link for each already known destination. Each destination knew how to decide if the document was suitable for it, but had no possibility of not sending the document to the next link. The behaviour of chain was implemented in the HandleRequest in the abstract class, here there is the sequence diagram.

How the chain works

As it’s shown, the abstract class calls an abstract method called processRequest, which does the actual processing of the request, implemented in the concrete classes. After calling this method the next link in chain is called. This order can be reversed, so first call the next chain, and then process the request.  In our case, each link had no possibility of not calling the next link, if this possibility is needed, the processRequest method can return a boolean value to determine if request has to be processed by the next link or not.

*All diagrams are made with StarUML.