05 Dec 2023
The Chain of Responsibility design pattern is a behavioral pattern where a series of handler objects are chained together to handle a request. Each handler decides either to process the request or to pass it along the chain to the next handler. In C#, the Chain of Responsibility pattern typically involves the following main components:
-
Handler:
- Declares an interface for handling requests.
- Contains a reference to the next handler in the chain.
public abstract class Handler { protected Handler successor; public void SetSuccessor(Handler successor) { this.successor = successor; } public abstract void HandleRequest(int request); } -
Concrete Handlers:
- Implement the
Handlerinterface. - Handle requests they are responsible for and pass along requests they cannot handle.
public class ConcreteHandlerA : Handler { public override void HandleRequest(int request) { if (request <= 10) { Console.WriteLine($"ConcreteHandlerA handles the request: {request}"); } else if (successor != null) { successor.HandleRequest(request); } } }public class ConcreteHandlerB : Handler { public override void HandleRequest(int request) { if (request > 10 && request <= 20) { Console.WriteLine($"ConcreteHandlerB handles the request: {request}"); } else if (successor != null) { successor.HandleRequest(request); } } }public class ConcreteHandlerC : Handler { public override void HandleRequest(int request) { if (request > 20) { Console.WriteLine($"ConcreteHandlerC handles the request: {request}"); } else if (successor != null) { successor.HandleRequest(request); } } } - Implement the
-
Client:
- Initiates the request and passes it to the first handler in the chain.
class Client { static void Main() { Handler handlerA = new ConcreteHandlerA(); Handler handlerB = new ConcreteHandlerB(); Handler handlerC = new ConcreteHandlerC(); handlerA.SetSuccessor(handlerB); handlerB.SetSuccessor(handlerC); // Send requests to the chain handlerA.HandleRequest(5); handlerA.HandleRequest(15); handlerA.HandleRequest(25); } }
In this example:
Handleris the abstract class that declares the interface for handling requests and maintains a reference to the next handler in the chain.ConcreteHandlerA,ConcreteHandlerB, andConcreteHandlerCare concrete implementations of theHandlerclass. Each handler decides whether to handle the request or pass it to the next handler in the chain.- The
Clientcreates instances of the handlers and sets up the chain. It initiates requests by calling theHandleRequestmethod on the first handler in the chain.
The Chain of Responsibility pattern allows multiple objects to handle a request without the client needing to know which object will handle it. Handlers are organized into a chain, and each handler in the chain decides whether to handle the request or pass it to the next handler. This promotes flexibility and reduces coupling between the sender and receivers of a request.