Tutorials Design Patterns Mastery

Chain of Responsibility: Middleware & Pipeline Architecture

On this page

Chain of Responsibility

The Chain of Responsibility allows multiple objects to handle a request without the sender knowing which object will ultimately process it. The request is passed along a "Chain," and each handler decides whether to process it or pass it to the next link.

1. Real-World .NET Example: Middleware

In ASP.NET Core, every request goes through a pipeline. Authentication -> Routing -> Authorization -> Endpoint. If Authentication fails, it "Short-circuits" and returns a 401. If it succeeds, it calls next().

public void Handle(Request req) 
{
    if (CanHandle(req)) 
    {
        Process(req);
    }
    else if (_next != null) 
    {
        _next.Handle(req); // Pass to next link in chain
    }
}

2. Why use it?

It follows the Single Responsibility Principle. You can create a LoggingHandler and a SpamCheckHandler as separate classes. You can then reorder them or add new ones at runtime without changing any existing logic.

4. Interview Mastery

Q: "How is a Chain of Responsibility different from a Decorator?"

Architect Answer: "Structural vs Behavioral intent. A **Decorator** is about *Adding Functionality* to an object (e.g., adding encryption to a stream). A **Chain of Responsibility** is about *Choosing a Handler* for a request. In a chain, a handler might decide to stop the request entirely (Short-circuiting). In a decorator, the call almost always passes through every single layer of the cake. Decorator is a wrapper; Chain is a pipeline."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Design Patterns Mastery
Course syllabus
1. Introduction to Design Patterns
2. Creational Patterns
3. Structural Patterns
4. Behavioral Patterns
5. Modern Enterprise & Cloud Patterns
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details