Implementing the Chain of Responsibility pattern
The Chain of Responsibility is a GoF behavioral pattern that chains classes to handle complex scenarios efficiently, with limited effort. Once again, the goal is to take a complex problem and break it into multiple smaller units.
Goal
The goal of the Chain of Responsibility pattern is to chain multiple handlers that each solve a limited number of problems. If a handler cannot solve the specific problem, it passes the resolution to the chain’s next handler. There could be a default handler executing some logic at the end of the chain, such as throwing a custom exception (for example, OperationNotHandledException
) or a handler that makes sure of the opposite (in other words, that nothing happens, especially no exception).
Design
The most basic Chain of Responsibility starts by defining an interface that handles a request (IHandler
). Then we add classes that handle one or more scenarios (Handler1
and Handler2
):