Course contentsShow
← C#
Lesson 109 of 1,9081. C# Language FoundationsFree lesson

Chain of Responsibility

Pass requests along a chain of handlers to decouple senders from receivers.

In this lesson, you will learn how to use the Chain of Responsibility pattern to process requests by passing them through a sequence of potential handlers until one takes action.

The Core Idea

Imagine you are at an office where a request (like a refund) passes through a chain of employees. If the first person can handle it, they do; if not, they pass it to their manager, and so on. In C#, this pattern allows you to decouple the "sender" of a request from the "receiver," because the sender doesn't need to know which specific object will ultimately handle the request.

Building the Chain

Each handler in the chain holds a reference to the "next" handler. If a handler cannot process a request, it calls the next handler.

public abstract class Handler 
{
    protected Handler? Next;
    public void SetNext(Handler next) => Next = next;
    
    public abstract void Handle(string request);
}

public class SupportHandler : Handler 
{
    public override void Handle(string request) 
    {
        if (request == "simple") 
            Console.WriteLine("Support handled it.");
        else 
            Next?.Handle(request); // Pass the buck!
    }
}

Why Use This?

  1. Decoupling: You don't need a giant if-else or switch block in your main logic to check every possible condition.
  2. Flexibility: You can change the order of handlers or add new ones at runtime without changing the code that sends the request.
  3. Single Responsibility: Each class in your chain only cares about one type of request or one specific logic gate.

In your application, you would create an instance of each handler and link them using SetNext. When the first handler receives the request, it automatically cascades through the chain until someone accepts it or the end is reached. This is perfect for scenarios like logging systems, permission checks, or request validation where multiple rules might apply.

Key Takeaway: The Chain of Responsibility pattern lets you pass a request along a linked sequence of handlers, allowing each to decide whether to process the request or forward it to the next link in the chain.