Chain of Responsibility Design Pattern

Chain of responsibility is a behavioral design pattern.

The aim of this design pattern is formally explained like this: “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.”

A chain can consist of many objects that are able to handle the incoming request. Each object decides whether it can handle the request. If it can, it handles it. If not, it passes the request to the next object in the chain. This model enables loose coupling between the sender and receiver of a request.

The sender should not need to know which receiver will handle the request. This reduces dependecies between objects.

Let’s understand this design pattern better through an example code.

Let’s say we are in the cargo business. We have three types of vehicles. We send items onto a conveyor belt and let our system decide which vehicle to load them onto.

There is a handler which defines a common interface for handling the requests. It is an interface or abstract class.

All objects implement the handler and provide their specific implementations. Each object has a link to the next handler in the chain. If it can not handle the request, it pass the request to the next handler in the chain.

Client, creates the instances of handlers, link them together and starts the chain of handling by calling handleRequest method.