What is Chain of Responsibility Design Pattern
When implementing a set of functions the functions need to divide into smaller elements to reduce complexity and increase maintainability. But with the complexity of the problem, the tight coupling can result as a solution for this Behavior Design Patterns introduced to divide the functionalities among the modules effectively, and the Chain of Responsibility Pattern is one of them.
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.
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
As we discussed this pattern fulfills its request by implementing a set of objects called handlers.
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.
Complete Source code available here.