The Chain of Responsibility design pattern is a behavioral design pattern that allows an object to pass a request along a chain of handlers. Each handler in the chain decides either to process the request or to pass it along the chain to the next handler.
This pattern is frequently used in the chain of multiple objects, where each object either handles the request or passes it on to the next object in the chain if it is unable to handle that request.
This pattern encourages loose coupling between sender and receiver, providing freedom in handling the request.
Example: In a customer support system, requests are handled step-by-step through a chain of support levels—starting with a Bot for simple issues, then a Junior Executive, and finally a Senior Engineer for complex problems if needed.
A Client sends a request to Handler 1, which is the first point in the processing chain.
If Handler 1 cannot fully handle the request, it forwards it to Handler 2, and then to Handler 3 if needed.
Each handler decides independently whether to process the request or pass it forward, forming a chain of responsibility.
Real-World Analogy
Imagine a customer service department with multiple levels of support staff, each responsible for handling different types of customer inquiries based on their complexity. The chain of responsibility can be illustrated as follows:
Level 1 Support: This represents the first point of contact for customer inquiries. Level 1 support staff handle basic inquiries and provide general assistance. If they cannot resolve the issue, they escalate it to Level 2 support.
Level 2 Support: This level consists of more experienced support staff who can handle more complex issues that Level 1 support cannot resolve. If Level 2 support cannot resolve the issue, they escalate it to Level 3 support.
Level 3 Support: This is the highest level of support, consisting of senior or specialized staff who can handle critical or highly technical issues. If Level 3 support cannot resolve the issue, they may involve other departments or experts within the organization.
The real life example of chain of responsibility design pattern are:
In graphical user interfaces (GUIs), events like mouse clicks or key presses can be handled by a chain of listeners. Each listener checks if it can handle the event, passing it along the chain if it can't. This way, multiple components can respond to the same event without being tightly linked.
In logging systems, you might have different levels of loggers (like INFO, WARN, ERROR). Each logger can handle specific log messages. If one logger can’t process a message (for example, if it's below its level), it passes it to the next logger in the chain.
In security systems, access requests can be processed by a series of handlers that check permissions. For instance, one handler might check user roles, while another checks specific permissions. If one handler denies access, it can pass the request to the next handler for further evaluation.
Components
The Chain of Responsibility Pattern consists of the following key components:
Handler Interface or Abstract Class: This is the base class that defines the interface for handling requests and, in many cases, for chaining to the next handler in the sequence.
Concrete Handlers: These are the classes that implement how the requests are going to be handled. They can handle the request or pass it to the next handler in the chain if it is unable to handle that request.
Client: The request is sent by the client, who then forwards it to the chain’s first handler. Which handler will finally handle the request is unknown to the client.
Working
This pattern works by passing a request along a chain of handlers until one of them handles the request.
A request is sent by the client without knowing which handler will process it.
The request is passed from one handler to the next in the chain.
Each handler checks whether it can handle the request.
If it can, it processes the request; otherwise, it forwards it to the next handler.
Uses
This pattern is used when multiple objects may handle a request and the handler is not known in advance.
Handling requests in multiple levels (e.g., approval systems).
Implementing logging frameworks with different log levels.
Designing event handling systems in GUI applications.
Managing authentication and authorization chains.
Implementation Example
Problem Statement
In a customer support system, requests are processed based on priority through three levels of support. Level 1 handles basic issues, Level 2 manages more complex problems, and Level 3 deals with critical issues that cannot be resolved by the lower levels.
Benefit of Using the Chain of Responsibility in this scenario
The Chain of Responsibility pattern fits this situation by creating a sequence of handlers where each one either processes the request or passes it to the next. It improves flexibility and scalability by allowing handlers to be added or removed without changing the client code.
Defines the interface for handling requests. Includes methods for handling requests (handleRequest()) and setting the next handler in the chain (setNextHandler()).
2. Concrete Handlers
Implement the SupportHandler interface. Each handler is responsible for handling requests based on its assigned priority level. If a handler can handle the request, it processes it; otherwise, it passes the request to the next handler in the chain.
Complete code for the above example
Output
Level 1 Support handled the request.
Level 2 Support handled the request.
Level 3 Support handled the request.
Advantages
The pros of chain of responsibility design pattern are
The pattern makes enables sending a request to a series of possible recipients without having to worry about which object will handle it in the end. This lessens the reliance between items.
New handlers can be easily added or existing ones can be modified without affecting the client code. This promotes flexibility and extensibility within the system.
The sequence and order of handling requests can be changed dynamically during runtime, which allows adjustment of the processing logic as per the requirements.
It simplifies the interaction between the sender and receiver objects, as the sender does not need to know about the processing logic.
Disadvantages
The cons of chain of responsibility design pattern are
The chain should be implemented correctly otherwise there is a chance that some requests might not get handled at all, which leads to unexpected behavior in the application.
The request will go through several handlers in the chain if it is lengthy and complicated, which could cause performance overhead. The processing logic of each handler has an effect on the system’s overall performance.
The fact that the chain has several handlers can make debugging more difficult. Tracking the progression of a request and determining which handler is in charge of handling it can be difficult.
It may become more difficult to manage and maintain the chain of responsibility if the chain is dynamically modified at runtime.