Chain of Responsibility Design Pattern

Photo by JJ Ying on Unsplash

What is Chain of Responsibility Design Pattern

On a very basic level what the chain of responsibility pattern does is that its chain of objects handling user requests. for handling these requests this pattern uses a set of objects called “handlers”. and each of these handlers has unique functions to complete the overall task.

How Handlers Work in Chain of Responsibility Pattern (Image from CodeNuclear)

Each request comes from the Client object sometimes needs to reach each handler object or it may fulfill the request from reaching to only one handler or it might need to reach all the necessary handlers depending on the implementation.

This makes the large functionalities into a more modular approach.

Implementation of Chain of Responsibility Pattern

Implementing a Handler (Image from ITNext)

And each handler knows about their successor.

Let’s Take a sample scenario of implementing an Email filtering system for an organization, this organization is super secured and it has all the emails and does not accept outside emails.

First, we implement a POJO for the Email.

Next for handler objects there should be a specific format and each handler should follow the same structure, for this, we create an abstract class for the handler object with the ability to define it’s sucessor.

And this email system ensures email safety by checking the email domain is verified by the organization, is the intended receiver is actually in the system, and the email body has malicious contents. For each of these functionalities, we create separate handlers and a specific handler for directing the first request to the relevant handler.

Now from a client object first we have to create the objects from handlers and set their successors. it will define the order of the chain.

And if the company at some time decided to receive the email from the outside sources without implementing from scratch they only need to change the hanlders succesor level and ignore the domain handler like below.

starterHandler.setSuccessor(directoryHandler);        directoryHandler.setSuccessor(contentHandler);    

Software Engineer