Chain of Responsibility
Last updated
Last updated
Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers.
Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.
The Chain of Responsibility design pattern is a behavioral pattern where a request is passed through a chain of handlers.
Each handler decides either to process the request or pass it to the next handler in the chain.
This pattern promotes loose coupling between senders and receivers of a request.
In JavaScript, you can implement the Chain of Responsibility pattern using objects and their methods.
In this example:
We have a base Handler
class defining the interface for handling requests and holding a reference to the next handler in the chain.
Concrete handlers (ConcreteHandler1
, ConcreteHandler2
, ConcreteHandler3
) implement the actual handling logic. If they can't handle the request, they pass it to the next handler in the chain.
The client code sets up the chain and sends requests to the first handler in the chain.
This way, each handler in the chain has the opportunity to handle the request or pass it to the next handler until the request is processed or the end of the chain is reached.