The Chain of Responsibility Pattern is a behavioral design pattern that allows a
request to be passed through a chain of handlers until one of them processes it.
This approach promotes flexibility by decoupling the sender and receiver,
enabling dynamic and customizable request handling. It is particularly useful in
scenarios where multiple objects can handle a request, but the specific handler
is determined at runtime.
typeHandler={handleRequest(request: string):void;// Pass the request data
setSuccessor(successor: Handler|undefined):void;};classAbstractHandlerimplementsHandler{protectedsuccessor: Handler|undefined=undefined;constructor(protectedkind: string){}setSuccessor(successor: Handler|undefined):void{this.successor=successor;}handleRequest(request: string):void{if(this.canHandle(request)){this.handle(request);}elseif(this.successor!==undefined){this.successor.handleRequest(request);}}protectedcanHandle(_request: string):boolean{returntrue;// Default implementation, subclasses can override
}protectedhandle(_request: string):void{// Subclasses should implement this to define their handling logic
}}classConcreteHandler1extendsAbstractHandler{protectedhandle(request: string):void{console.log(`${this.kind} handled request: ${request}`);}}classConcreteHandler2extendsAbstractHandler{protectedcanHandle(request: string):boolean{returnrequest.startsWith("prefix_");// Example condition
}protectedhandle(request: string):void{console.log(`${this.kind} handled request: ${request}`);}}constclient={run():void{consthandler1=newConcreteHandler1("foo");consthandler2=newConcreteHandler2("bar");handler2.setSuccessor(handler1);// Set the chain
handler2.handleRequest("some_request");// Will be handled by handler1
handler2.handleRequest("prefix_another_request");// Will be handled by handler2
}};client.run();