Chain of Responsibility
Pass a request down a chain of handlers β each one decides to handle it or kick it to the next. The sender never knows who actually does the work.
Intent & Description
π― Intent
Decouple the thing that sends a request from the thing that handles it, with multiple potential handlers in play.
π Context
You have requests that need different processing depending on type, priority, or context β middleware pipelines, auth checks, logging layers, support ticket escalation. Hard-coding which handler does what creates a branching mess.
π‘ Solution
Build a chain of handler objects. Each handler has a reference to the next. When a request arrives, the handler either processes it or calls next.handle(request). Handlers are added, removed, or reordered without touching each other or the client.
Real-world Use Case
Source
π TL;DR
Chain of handlers. Each one either handles the request or passes it along. Sender doesn’t care who handles it. Add a fallback handler or requests disappear silently.
Advantages
- Add, remove, or reorder handlers without touching the client or other handlers.
- Each handler has one job β clean Single Responsibility.
- New handlers plug in without breaking anything downstream.
Disadvantages
- Requests can fall off the end of the chain unhandled if you forget a catch-all fallback.
class Handler {
setNext(handler) {
this.nextHandler = handler;
return handler;
}
handle(request) {
if (this.nextHandler) {
return this.nextHandler.handle(request);
}
return null;
}
}
class MonkeyHandler extends Handler {
handle(request) {
if (request === "Banana") {
return `Monkey: I'll eat the ${request}.`;
}
return super.handle(request);
}
}