Pattern: Chain of Responsibility

The Chain of Responsibility pattern is used to pass a request along a chain of handlers. Each handler decides either to process the request or to pass it to the next handler in the chain. Here's a simple example of the Chain of Responsibility pattern in C#:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System;

// Handler interface
public interface IHandler
{
    IHandler SetNext(IHandler handler);
    string HandleRequest(int request);
}

// ConcreteHandler class
public class ConcreteHandler : IHandler
{
    private IHandler _nextHandler;

    public IHandler SetNext(IHandler handler)
    {
        _nextHandler = handler;
        return handler;
    }

    public string HandleRequest(int request)
    {
        if (request >= 0 && request < 10)
        {
            return $"Handler 1: {request}";
        }
        else if (_nextHandler != null)
        {
            return _nextHandler.HandleRequest(request);
        }
        else
        {
            return "No handler can process the request.";
        }
    }
}

class Program
{
    static void Main()
    {
        // Create the chain of handlers
        IHandler handler1 = new ConcreteHandler();
        IHandler handler2 = new ConcreteHandler();
        IHandler handler3 = new ConcreteHandler();

        handler1.SetNext(handler2).SetNext(handler3);

        // Process requests
        Console.WriteLine(handler1.HandleRequest(5));
        Console.WriteLine(handler1.HandleRequest(15));
    }
}

In this example:


- IHandler is the handler interface, defining the `SetNext` method to set the next handler and the `HandleRequest` method to process the request.

- ConcreteHandler is a concrete handler class implementing the `IHandler` interface. It processes requests in a specific range and passes the request to the next handler if applicable.


The Main method creates a chain of handlers and processes requests. This is a simplified example, and in a real-world scenario, handlers might be more complex, and the chain may be dynamically constructed.

Comments

Popular posts from this blog

Creating a website with strong SEO

Securing Your ASP.NET Core Blazor App

Web3 in a couple words explained