Chain of ResponsibilityVSDecorator
The Problem
Scenario A β Chain of Responsibility territory: Your document approval workflow goes through team lead, manager, then compliance. Each can approve, reject (stopping the chain), or escalate. If the amount is under $100, the team lead approves directly without passing further.
Scenario B β Decorator territory: Your HTTP response pipeline adds gzip compression, CORS headers, and cache-control headers. Every response goes through all three steps β none can short-circuit. Each adds something and passes the response along.
Why They Look Alike
Both create a chain of objects where each links to the next. Both use the same interface. Both process a request sequentially. The wiring code looks identical: A β B β C.
The Core Difference
| Aspect | Chain of Responsibility | Decorator |
|---|---|---|
| Can stop early | Yes β a handler can reject/handle without passing on | No β always delegates to the wrapped object |
| Purpose | Find the right handler or filter | Add behavior on top of existing behavior |
| Request flow | May stop at any link | Always flows through all wrappers |
| Handler knows next? | Optionally (can end the chain) | Always wraps exactly one object |
| Return value | Handler's result OR next handler's result | Enhanced result of the wrapped object |
| Analogy | Support ticket escalation β someone handles it | Gift wrapping β each layer adds wrapping paper |
| Real-world | Express middleware, NestJS guards, approval pipelines | Logging decorator, caching decorator, compression |
One sentence: CoR can short-circuit (someone handles it and stops); Decorator always passes through (everyone adds their layer).
Side-by-Side Code
Chain of Responsibility β Approval pipeline
| 1 | interface ApprovalHandler { |
| 2 | setNext(handler: ApprovalHandler): ApprovalHandler; |
| 3 | approve(request: PurchaseRequest): ApprovalResult; |
| 4 | } |
| 5 | |
| 6 | abstract class BaseApprovalHandler implements ApprovalHandler { |
| 7 | private next: ApprovalHandler | null = null; |
| 8 | |
| 9 | setNext(handler: ApprovalHandler): ApprovalHandler { |
| 10 | this.next = handler; |
| 11 | return handler; |
| 12 | } |
| 13 | |
| 14 | approve(request: PurchaseRequest): ApprovalResult { |
| 15 | if (this.next) return this.next.approve(request); |
| 16 | return { approved: false, reason: 'No handler could approve' }; |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | class TeamLeadApprover extends BaseApprovalHandler { |
| 21 | approve(request: PurchaseRequest): ApprovalResult { |
| 22 | if (request.amount < 100) { |
| 23 | return { approved: true, approver: 'Team Lead' }; // STOPS here |
| 24 | } |
| 25 | return super.approve(request); // pass to next |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | class ManagerApprover extends BaseApprovalHandler { |
| 30 | approve(request: PurchaseRequest): ApprovalResult { |
| 31 | if (request.amount < 1000) { |
| 32 | return { approved: true, approver: 'Manager' }; // STOPS here |
| 33 | } |
| 34 | return super.approve(request); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // Chain: teamLead β manager β director |
| 39 | const teamLead = new TeamLeadApprover(); |
| 40 | teamLead.setNext(new ManagerApprover()).setNext(new DirectorApprover()); |
| 41 | teamLead.approve({ amount: 50 }); // handled by TeamLead, stops |
| 42 | teamLead.approve({ amount: 500 }); // passed to Manager, stops |
Decorator β Response enhancement
| 1 | interface ResponseHandler { |
| 2 | handle(req: Request): Promise<Response>; |
| 3 | } |
| 4 | |
| 5 | class CoreHandler implements ResponseHandler { |
| 6 | async handle(req: Request): Promise<Response> { |
| 7 | return { status: 200, body: await this.fetchData(req), headers: {} }; |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | class CorsDecorator implements ResponseHandler { |
| 12 | constructor(private wrapped: ResponseHandler) {} |
| 13 | |
| 14 | async handle(req: Request): Promise<Response> { |
| 15 | const res = await this.wrapped.handle(req); // ALWAYS delegates |
| 16 | res.headers['Access-Control-Allow-Origin'] = '*'; |
| 17 | return res; // adds CORS, passes everything through |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | class CompressionDecorator implements ResponseHandler { |
| 22 | constructor(private wrapped: ResponseHandler) {} |
| 23 | |
| 24 | async handle(req: Request): Promise<Response> { |
| 25 | const res = await this.wrapped.handle(req); // ALWAYS delegates |
| 26 | res.body = gzip(res.body); |
| 27 | res.headers['Content-Encoding'] = 'gzip'; |
| 28 | return res; // adds compression, passes everything through |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | // Every decorator runs β no short-circuiting |
| 33 | const handler = new CompressionDecorator( |
| 34 | new CorsDecorator( |
| 35 | new CoreHandler() |
| 36 | ) |
| 37 | ); |
Decision Rules
| Signal | Choose | Why |
|---|---|---|
| A handler may stop the chain (reject, handle completely) | CoR | Short-circuit capability |
| Every step must run (adds behavior, never skips) | Decorator | Always delegates through |
| Finding the right handler for a request | CoR | First match handles it |
| Stacking enhancements on an object | Decorator | Each wrapper adds a layer |
| Express middleware (next() is optional) | CoR | Middleware can end the response |
| Logging/caching/compression wrappers | Decorator | Always pass through |
| Auth guards (deny = stop, allow = continue) | CoR | Can short-circuit on denial |
The Trick Question
"Your NestJS middleware pipeline: auth checks β rate limiting β request logging β route handler. Auth and rate limiting can reject. Logging always passes through. Which pattern?"
This is Chain of Responsibility overall β because auth and rate limiting can short-circuit (return 401 or 429 without calling next()). The fact that logging always passes through doesn't make it a Decorator; in CoR, some handlers choose to always pass, some choose to stop. The capability to stop is what defines CoR.
If NONE of the handlers could ever stop β all always pass through β then it would be Decorator.
Interview Angles
Q: Can you mix both in one pipeline? Yes. Express middleware is CoR (any middleware can end the response), but you might use Decorator within a single middleware to wrap the response object with additional behavior. The pipeline is CoR; individual enhancements are Decorator.
Q: How does NestJS organize these? Guards = CoR (can reject). Interceptors = Decorator-like (wrap execution, always continue). Pipes = CoR (can throw validation error). Middleware = CoR (can skip next()). The framework uses both patterns for different purposes.
Q: What about error handling middleware?
Error handling middleware in Express ((err, req, res, next)) is CoR. Each error handler decides: handle the error and respond, or pass to the next error handler. The first one that matches handles it.
Q: Performance difference? Minimal. Both are O(n) through the chain. CoR may be faster on average because it short-circuits. Decorator always runs all layers. The difference only matters with very long chains.