Also known as CoR, Chain of Command

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.

Problem

Imagine that you're working on an online ordering system. You have to restrict access to the system so that only authorized users would be able to create orders. Besides, some users that have special permissions should act as administrators with full access to all orders.

Since every request to the system would contain user credentials, the authentication could be performed at any time. But if the program fails to authenticate a user, any further checks would be pointless. Thus, the checks should be performed in the particular order.

Someone noticed that it is unsafe to pass raw data straight to the processing code, so the extra validation step was created to sanitize request data.

Later someone else suggested that system is vulnerable to brute force password cracking, so the additional check was added to filter repeating requests that contain the same username.

You even added caching to the ordering form to increase its performance under heavy load.

Unfortunately, with every new feature, the code became more and more bloated. Moreover, you had to duplicate some of the code in several places to protect other pages that required just a portion of these checks.

The system became too hard and expensive to maintain. But one day you received a task to refactor the whole thing...

Solution

Like many other behavioral design patterns, the Chain of Responsibility relies on converting particular behaviors into their own objects. In our case, each check would move to the separate class with a single execute method. The request data will be passed to this method as an argument.

Now, the interesting part. Chain of Responsibility suggests putting reference fields into each of these classes in order to link several handlers together into one chain. Handlers would pass execution to other handlers once they've finished with their processing. The request would travel along the chain until all handlers had a chance to process it.

And the last thing. A handler does not have to pass a request further. There are two popular ways to exploit this idea.

In our example with access restriction, a handler may terminate all further checks if the current one fails. Checking all others is just a waste of resources when you know that at least one of them fails.

But there's another approach where a handler passes the request along only when it's not able to process it.

This option is quite common when dealing with events in graphical user interface components. For instance, when a user clicks a button, the event is propagated through a chain of components that starts with the button, goes along its parents, like forms and panels, and ends up with the main application window. The event is processed by the first component in that chain capable of handling it.

This example is also noteworthy because it shows that a chain can always be extracted from a tree structure.

It's crucial that all handlers follow the same interface. It would let you compose the chain from various handlers without coupling to their concrete classes. Each concrete handler would only need to know that the following handler has the execute method. It would also be possible to alter the chain at runtime.

Real-World Analogy

Technical support

You've just bought a new video card for your PC. Windows has detected and enabled it automatically. But your beloved Linux, however, refused to work with the new hardware. With a small glimpse of hope, you call the tech support.

The first thing you hear is a robot's voice of the autoresponder. It suggests nine popular solutions to various problems, none of which is related to yours. After a while, robot connects you to the live operator.

Alas, the operator can't suggest anything specific. It only shoots you with long excerpts from FAQ section. After hearing "did you try turning it off and on again" for the 10th time, you ask to connect you to a proper engineer.

The operator quickly passes your call to the engineer that inhabits a lonely server room in a basement of an office building. Finally, the engineer tells you where to download proper drivers for the card and how to install them in Linux. You end the call, bursting with joy.

Structure

Chain Of Responsibility pattern structure
  1. Handler defines the standard interface for all concrete handlers. At the minimum, it should contain two methods: execute and getNext. The execution method should have sufficient parameters for accepting request data.

    In most cases, it's worth adding an abstract base handler class, containing a field for storing a reference to next handler. Otherwise, the field should be declared in all concrete handlers.

    You can describe additional methods for changing the value of the reference field if you want to be able to alter a chain dynamically.

  2. Concrete handlers contain the actual code for processing requests. Handlers are usually self-contained and immutable, accepting all necessary data just once, via constructor parameters.

  3. Client may compose chains just once or do it dynamically, depending on the program logic. Note that a request could be sent to any handler in the chain, it does not always have to be the first one.

Pseudocode

In this example, the Chain of Responsibility is responsible for deciding which of the GUI classes would be responsible for processing an event triggered by users. The GUI elements are structured into a tree. The Container class that renders the main window is the root of the tree. The middle layer composed with Panels. The leaf elements are Buttons, TextEdits and others.

All of the elements are capable of receiving user events, such as clicks. They bubble-up events to their parents until there's an element capable of processing them.

// Abstract handler interface.
abstract class Component is
    field onClick: function

    // Basic handling method. It will be called when no other handler is capable
    // of processing a click.
    method click(x, y) is
        if (onClick != null)
            onClick(context)

    abstract method render(x, y, width, height)


// Concrete component implementation. It inherits basic functionality from the
// abstract handler.
class ContainerComponent extends Component is
    // Complex concrete component, which has references to other components.
    field children: array of Component

    method add(child) is
        children.add(child)

    // Component stores its references here.
    method click(x, y) is
        if (onClick != null) then
            onClick(context)
        else if (child.atCoord(x,y))
            child.click(x, y)


// If can't handle a click yourself, then pass it to your child component if you
// have one at a click's coordinate.
class Button extends Component is
    method render() is
        Draw a button.

class Panel extends ContainerComponent is
    method render() is
        Draw a panel and its children.


// Client code.
class Application is
    // Each application configures the chain differently.
    method createUI() is
        panel = new Panel(0, 0, 400, 800)
        ok = new Button(250, 760, 50, 20, "OK")
        ok.onClick({ ... })
        panel.add(ok);
        cancel = new Button(320, 760, 50, 20, "Cancel")
        cancel.onClick({ ... })
        panel.add(cancel)

    // Imagine what happens here.
    method test() is
        panel.click(251, 761)

Applicability

When a program has several handlers capable of processing different requests, but you don't know in advance what type of request to expect.

You link several handlers into one chain. Request travels through the chain until it lands on a handler that can process it.

When it's important to execute handlers in a certain order.

Chain of Responsibility allows executing handlers one by one in a given order.

When a set of objects handling requests and their order should change dynamically.

Chain of Responsibility allows altering references withing an existing chain to insert, remove or reorder some handlers.

How to Implement

  1. Define the Handler interface with a single execute method. Decide how would you pass request details into the method. Usually, the most flexible way is to pass an entire request object to the method.

  2. Add a method for retrieving next handler in a chain to the interface.

  3. It might be worth creating a base abstract class derived from the Handler interface. It would contain the actual field for storing a reference to a next handler and implement the nextHandler method. The field would get initial value from a constructor parameter. The class could also have a method for overriding reference to next handler, but it only required if you plan to modify chains in runtime.

  4. Create Concrete Handlers and implement the actual handling code. Depending on the logic of your app, a handler should either launch next handler in the chain or terminate the execution.

  5. The chain can be composed by the direct Clients or some external entity or factory.

  6. Client may trigger any handler in the chain. The call will be passed recursively along the chain until it reaches the end or until some handler refuses to pass the request further.

  7. Client should be aware of the dynamic nature of the chain. Sometimes it consists from a single link. Some requests might not reach the end of a chain. Some request might reach the end of a chain unhandled.

Pros and Cons

  • Reduces coupling between senders of requests and their receivers.
  • Follows the Single Responsibility Principle.
  • Follows the Open/Closed Principle.
  • Some requests may end up unhandled.

Relations with Other Patterns

  • Chain of Responsibility, Command, Mediator and Observer address various ways of connecting senders and receivers of requests:

    • Chain of Responsibility passes a request sequentially along a dynamic chain of potential receivers until one of them handles a request.

    • Observer passes a request to all concerned receivers at the same time but allows them to subscribe and unsubscribe from receiving further requests dynamically.

    • Command establishes a one-directional connection from senders to receivers.

    • Mediator has senders and receivers reference each other indirectly.

  • Chain of Responsibility is often applied in conjunction with Composite. In this case, a component's parent can act as its successor.

  • Chain of Responsibility can use Command as a request to execute some action over a set of objects.

  • Chain of Responsibility and Decorator have very common class structures. They both rely on the recursive composition to pass execution through a series of objects. But there are also several crucial differences.

    The Chain of Responsibility handlers can execute arbitrary actions, independent of each other. They can also terminate further chaining of the request at will. On the other hand, various Decorators extend a particular behavior and suppose to keep its interface consistent. Also, Decorators are not allowed to break the execution chain at will.

Implementations in Different Programming Languages

Java