Junior — Middle
Can you give an example of implementing the Chain of Responsibility pattern in programming code?
sobes.tech AI
Answer from AI
The Chain of Responsibility pattern allows passing a request along a chain of handlers until one of them handles the request.
Example in C#:
// Abstract handler
abstract class Handler
{
protected Handler next;
public void SetNext(Handler nextHandler) {
next = nextHandler;
}
public virtual void Handle(string request) {
if (next != null) {
next.Handle(request);
}
}
}
// Concrete handlers
class ConcreteHandlerA : Handler
{
public override void Handle(string request) {
if (request == "A") {
Console.WriteLine("Handled by ConcreteHandlerA");
} else {
base.Handle(request);
}
}
}
class ConcreteHandlerB : Handler
{
public override void Handle(string request) {
if (request == "B") {
Console.WriteLine("Handled by ConcreteHandlerB");
} else {
base.Handle(request);
}
}
}
// Usage
var handlerA = new ConcreteHandlerA();
var handlerB = new ConcreteHandlerB();
handlerA.SetNext(handlerB);
handlerA.Handle("B"); // Will output: Handled by ConcreteHandlerB
In this example, the request is passed along the chain of handlers until a suitable one is found.