Chain of Responsibility Design Pattern - DeanHristov/ts-design-patterns-cheat-sheet GitHub Wiki
A Chain of Responsibility is a behavior design pattern that lets us transform particular behavior into a single stand-alone object called handler. Each handler decides whether to proceed further or reject the request. A simple UML diagram can be seen here
- It's essential to execute several handlers in a particular order
- Allow us to remove, insert, and re-order the handlers dynamically
abstract class BaseHandler {
private next: BaseHandler | undefined;
setNext(handler: BaseHandler): BaseHandler {
this.next = handler;
return this.next;
}
handle<T = object>(request: T): BaseHandler | string {
if (this.next) return this.next.handle(request);
return '';
}
}
class CustomHandler extends BaseHandler {
handle<T>(request: T): BaseHandler | string {
const shouldMoveFurther: boolean = true;
if (shouldMoveFurther) {
// Moving one step further
return super.handle(request);
}
// Rejecting the process further.
return 'Error! ....';
}
}
// CustomHandler = AuthHandler | AccessHandler | OtherHandler
const handler = new CustomHandler();
handler
.setNext(new AuthHandler(...))
.setNext(new AccessHandler(...))
.setNext(new OtherHandler(...));
handler.handle({ .... })
More info can be found on the wiki page.