Chain of Responsibility Pattern in Python
Chain of Responsibility decouples the sender from a specific receiver and makes handler order configurable.
What is Chain of Responsibility Pattern?
Chain of Responsibility decouples the sender from a specific receiver and makes handler order configurable.
Pass a request through handlers until one handles it.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
class Approver:
# Chain of Responsibility: offer a request to handlers in order.
def __init__(self, name, limit, next_approver=None):
self.name, self.limit, self.next = name, limit, next_approver
def approve(self, amount):
# Handle locally or pass the request along the chain.
if amount <= self.limit:
return f"{self.name} approved {amount}"
if self.next:
return self.next.approve(amount)
return "Declined"
chain = Approver("Lead", 100, Approver("Manager", 1000))
print(chain.approve(500))
Expected output
Manager approved 500
How it works
Each approver either handles the amount or forwards it to the next handler.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.