Chain of Responsibility Pattern
1. Introduction
The Chain of Responsibility Pattern is a behavioral design pattern that allows an object to pass a request along a chain of potential handlers until one of them handles the request. This pattern decouples the sender and receiver of a request and promotes a more flexible design.
2. Key Concepts
- **Handler**: An interface for handling requests.
- **ConcreteHandler**: Implements the Handler interface and handles requests.
- **Client**: Initiates the request and sends it to the chain of handlers.
- **Chain**: A sequence of handlers that can process requests.
3. How It Works
The request is sent to the first handler in the chain. If the handler can process the request, it does so; otherwise, it forwards the request to the next handler in the chain until a handler processes the request or the end of the chain is reached.
graph TD;
A[Client] --> B[Handler1]
B -->|Can Handle| C[Handler2]
C -->|Cannot Handle| D[Handler3]
D -->|Final Handler| E[End]
4. Code Example
Here is a simple implementation in Python:
class Handler:
def set_next(self, handler):
self.next_handler = handler
return handler
def handle(self, request):
if self.next_handler:
return self.next_handler.handle(request)
return None
class ConcreteHandlerA(Handler):
def handle(self, request):
if request == "A":
return "Handler A handled the request."
else:
return super().handle(request)
class ConcreteHandlerB(Handler):
def handle(self, request):
if request == "B":
return "Handler B handled the request."
else:
return super().handle(request)
client = ConcreteHandlerA()
handler_b = ConcreteHandlerB()
client.set_next(handler_b)
print(client.handle("A")) # Output: Handler A handled the request.
print(client.handle("B")) # Output: Handler B handled the request.
print(client.handle("C")) # Output: None
5. Best Practices
- Keep the chain flexible by allowing handlers to be added or removed.
- Ensure each handler is responsible for a specific type of request.
- Document the chain structure and responsibilities clearly.
6. FAQ
What is the main benefit of using the Chain of Responsibility pattern?
This pattern promotes loose coupling by allowing multiple objects to handle a request without knowing which object will ultimately handle it.
When should I use the Chain of Responsibility pattern?
Use this pattern when you have multiple handlers that can process a request, but you want to decouple requesting and handling objects.
Can I have more than one handler in the chain?
Yes, you can have multiple handlers in the chain, allowing for a flexible processing workflow.