Pass a request along a chain of handlers; each handler decides to process or forward it.
Chains handlers in sequence. Each handler either processes the request or passes it to the next handler, decoupling sender from receivers.
Handler interface with handle(request) and setNext(handler) methodsBaseHandler that stores the next handler and delegates by defaultsuper.handle()interface Handler { setNext(h: Handler): Handler; handle(n: number): string; }
abstract class BaseHandler implements Handler {
private next?: Handler;
setNext(h: Handler): Handler { this.next = h; return h; }
handle(n: number): string { return this.next?.handle(n) ?? `Unhandled: ${n}`; }
}
class SmallHandler extends BaseHandler {
handle(n: number) { return n < 10 ? `Small handled ${n}` : super.handle(n); }
}
class MediumHandler extends BaseHandler {
handle(n: number) { return n < 100 ? `Medium handled ${n}` : super.handle(n); }
}
// Build chain
const small = new SmallHandler();
small.setNext(new MediumHandler());
console.log(small.handle(5)); // Small handled 5
console.log(small.handle(50)); // Medium handled 50
console.log(small.handle(500)); // Unhandled: 500