The Chain of Responsibility pattern is a behavioral design pattern that allows a group of objects to handle a request sequentially, each potentially handling the request or passing it on to the next object in the chain until the request is handled or reaches the end of the chain.
In simple words, we can say that the chain of responsibility design pattern creates a chain of receiver objects for a given request. In this design pattern, normally, each receiver contains a reference to the next receiver. If one receiver cannot handle the request, it passes the same request to the next receiver, and so on. In this case, one receiver can handle the request in the chain, or one or more receivers can handle the request.
Components of Chain of Resposibility Pattern
- Handler Interface (or Abstract Class): This defines a common interface for all handlers. It typically includes a method for handling requests and a reference to the next handler in the chain.
- Concrete Handlers: These are the actual handlers in the chain. Each handler implements the Handler interface and contains logic to handle requests. If it can't handle a request, it passes it to the next handler in the chain.
- Client: This initiates the request and sends it to the first handler in the chain.