The Chain of Responsibility (CoR) pattern is a behavioral design pattern (Behavioral design patterns are concerned with algorithms and the assignment of responsibilities between objects) in TypeScript that allows an object to pass a request along a chain of handlers. This pattern provides a flexible and extensible way to handle requests without tightly coupling the sender and receiver objects.
How? Each handler in the chain decides either to process the request or pass it to the next handler in the chain.
Understanding the Basics:
Participants in the Pattern:
Handler Interface/Abstract Class: This defines the interface for handling requests.
Concrete Handlers: This implements the handling logic and decides whether to process the request or pass it to the next handler.
Client: This initiates the request and starts the chain.
Setting up the Handlers: To implement the CoR pattern in TypeScript, create a base handler interface/abstract class. Each concrete handler extends this base class and implements its handling logic.
interface Handler {
setNext(handler: Handler): Handler;
handleRequest(request: string): string | null;
}
abstract class AbstractHandler implements Handler {
private nextHandler: Handler | null = null;
public setNext(handler: Handler): Handler {
this.nextHandler = handler;
return handler;
}
public handleRequest(request: string): string | null {
if (this.nextHandler) {
return this.nextHandler.handleRequest(request);
}
return null;
}
}Creating Concrete Handlers:
class ConcreteHandlerA extends AbstractHandler {
public handleRequest(request: string): string | null {
if (request === 'A') {
return `Handler A is processing the request: ${request}`;
}
return super.handleRequest(request);
}
}
class ConcreteHandlerB extends AbstractHandler {
public handleRequest(request: string): string | null {
if (request === 'B') {
return `Handler B is processing the request: ${request}`;
}
return super.handleRequest(request);
}
}Using the Chain:
const handlerA = new ConcreteHandlerA();
const handlerB = new ConcreteHandlerB();
handlerA.setNext(handlerB);
// Client initiates the request
const resultA = handlerA.handleRequest('A');
// Output: "Handler A is processing the request: A"
const resultC = handlerA.handleRequest('C');
// Output: null (request not handled by any handler)Conclusion:
The Chain of Responsibility pattern in TypeScript offers a way to decouple request senders from receivers, providing flexibility and extensibility in handling various requests. By understanding the basic components and creating a chain of handlers, it becomes quite easy to implement a scalable and maintainable solution for managing complex request-processing scenarios like multi-step form submission, data synchronization, authentication and authorization etc.
No posts

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.