Member-only story
Understanding the Chain of Responsibility Design Pattern
A look at the middleware under the hood

There are 23 classic design patterns described in the original book Design Patterns: Elements of Reusable Object-Oriented Software. These patterns provide solutions to particular problems often repeated in software development.
In this article, I am going to describe how the Chain of Responsibility pattern works and when it should be applied.
Responsibility of Chain: Basic Idea
Wikipedia provides us with the following definition:
“The chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing 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.” — Wikipedia
On the other hand, the definition provided by the original book is as follows:
“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.”
On many occasions, we have a set of handlers (operations) that can be applied to an object (request) but we do not know, a priori, which handler should be applied to said object, nor whether one or more handlers should be applied to the request. The chain of responsibility pattern allows us to achieve more efficient and less coupled code since it avoids the previously mentioned issue. It also has other advantages regarding code maintainability. Here’s the UML pattern of this pattern:

These are the classes that comprise this pattern:
Handler
is the interface for handling requests. Although optional, most…