Chain of Responsibility Pattern
Learn how to pass a request along a chain of handlers so the sender does not need to know who deals with it, using expense approvals and request filters like those in servlets and Spring Security.
When you complain about a problem to a company, you usually start with the first-line support person. If they can fix it, the story ends there. If not, they pass it to a senior colleague. If the senior colleague cannot help either, it goes to a manager, and finally to a regional head. You do not need to know who will solve your problem. You tell the first person, and the request travels along a chain until someone can deal with it.
The Chain of Responsibility pattern puts this "pass it along" behaviour into code. A request is sent to the first handler in a chain. Each handler decides: "can I deal with this?" If yes, it does. If not, it passes the request to the next handler. The sender never needs to know which handler finally does the work.
01The problem: one place that knows every rule
A company has an expense approval policy:
- up to 10,000 rupees: a manager can approve,
- up to 100,000: a director,
- up to 1,000,000: the CEO.
A straightforward first version puts the decision in one method:
public void approve(ExpenseRequest request) {
long amount = request.amountInRupees();
if (amount <= 10_000) {
manager.approve(request);
} else if (amount <= 100_000) {
director.approve(request);
} else if (amount <= 1_000_000) {
ceo.approve(request);
} else {
throw new IllegalStateException("Needs board approval");
}
}This works, but look at its weaknesses:
- The caller, or a central method, must know every approver and the exact limits.
- Adding a new level, such as a "team lead" below the manager, means editing this method, and perhaps every place that has a similar chain of
ifchecks. - You cannot easily change the order or the set of approvers at run time, for example for a different department with a different policy.
- The rules of each approver are scattered in the big
if/else, and not in the approver's own class.
Loading the rest of the lesson…