Design Patterns

Pattern 13 sur 23, famille Comportement

Chain of Responsibility

En français : Chaîne de responsabilité

Faire passer une requête le long d'une chaîne de handlers : chacun la traite, l'arrête, ou la transmet au suivant.

Le problème

Une requête doit passer authentification, rate limiting, validation… Tout empiler dans le contrôleur crée un bloc de if monolithique, impossible à réordonner ou réutiliser.

La solution

Transformer chaque vérification en handler autonome qui possède une référence vers le suivant. On assemble la chaîne librement ; chaque maillon décide de couper ou de continuer.

Le pattern en action

  • Client
  • Rôle clé du pattern
  • Objet
  • Données ou état
  1. La requête entre dans le premier maillon.
  2. Token valide → transmission au maillon suivant.
  3. 12 req/min < 60 → suivant.
  4. Body invalide : Validation répond et coupe la chaîne. Le Controller n'est jamais atteint.
  5. Nouvelle requête, valide cette fois.
  6. Auth → RateLimit : next()
  7. RateLimit → Validation : next()
  8. Tous les maillons ont validé : le Controller traite la requête.

Une analogie

Le support technique : niveau 1, puis niveau 2, puis expert. Chacun résout ou escalade au suivant.

Quand l'utiliser

  • Middlewares HTTP (Laravel, Express, ASP.NET, Go)
  • Pipelines de validation / filtres
  • Gestion d'événements (bubbling DOM)

Avantages et limites

Avantages

  • Ordre des traitements configurable
  • Single Responsibility par maillon
  • Ajout / retrait de maillons sans toucher aux autres

Limites

  • Une requête peut traverser la chaîne sans être traitée
  • Débogage du flux moins direct

Implémentations

Le même exemple, écrit de façon idiomatique dans chaque langage.

Chain of Responsibility en Python

chain-of-responsibility.py 30 lignes
class Handler:
    def __init__(self):
        self._next: "Handler | None" = None

    def then(self, nxt: "Handler") -> "Handler":
        self._next = nxt
        return nxt

    def handle(self, req: dict) -> str:
        return self._next.handle(req) if self._next else "200 OK"


class Auth(Handler):
    def handle(self, req):
        return "401" if not req.get("token") else super().handle(req)

class RateLimit(Handler):
    def handle(self, req):
        return "429" if req.get("rpm", 0) > 60 else super().handle(req)

class Validation(Handler):
    def handle(self, req):
        return "422" if "body" not in req else super().handle(req)


chain = Auth()
chain.then(RateLimit()).then(Validation())

print(chain.handle({"token": "x", "rpm": 12}))               # 422
print(chain.handle({"token": "x", "rpm": 12, "body": {}}))   # 200 OK

Chain of Responsibility en TypeScript

chain-of-responsibility.ts 16 lignes
type Req = { token?: string; rpm: number; body?: unknown };
type Middleware = (req: Req, next: () => string) => string;

const auth: Middleware = (r, next) => (r.token ? next() : "401");
const rateLimit: Middleware = (r, next) => (r.rpm > 60 ? "429" : next());
const validate: Middleware = (r, next) => (r.body ? next() : "422");
const controller = () => "200 OK";

function chain(mws: Middleware[], final: () => string) {
  return (req: Req): string =>
    mws.reduceRight<() => string>((next, mw) => () => mw(req, next), final)();
}

const handle = chain([auth, rateLimit, validate], controller);
handle({ token: "x", rpm: 12 });           // "422"
handle({ token: "x", rpm: 12, body: {} }); // "200 OK"

Chain of Responsibility en Java

chain-of-responsibility.java 28 lignes
abstract class Handler {
    private Handler next;

    Handler then(Handler next) {
        this.next = next;
        return next;
    }

    String handle(Request r) {
        return next == null ? "200 OK" : next.handle(r);
    }
}

class Auth extends Handler {
    String handle(Request r) { return r.token() == null ? "401" : super.handle(r); }
}
class RateLimit extends Handler {
    String handle(Request r) { return r.rpm() > 60 ? "429" : super.handle(r); }
}
class Validation extends Handler {
    String handle(Request r) { return r.body() == null ? "422" : super.handle(r); }
}

record Request(String token, int rpm, String body) {}

Handler chain = new Auth();
chain.then(new RateLimit()).then(new Validation());
chain.handle(new Request("tok", 12, null)); // 422

Chain of Responsibility en C#

chain-of-responsibility.cs 25 lignes
abstract class Handler
{
    private Handler? _next;

    public Handler Then(Handler next) { _next = next; return next; }

    public virtual string Handle(Request r) => _next?.Handle(r) ?? "200 OK";
}

class Auth : Handler
{
    public override string Handle(Request r) => r.Token is null ? "401" : base.Handle(r);
}
class RateLimit : Handler
{
    public override string Handle(Request r) => r.Rpm > 60 ? "429" : base.Handle(r);
}

record Request(string? Token, int Rpm);

var chain = new Auth();
chain.Then(new RateLimit());
Console.WriteLine(chain.Handle(new Request("tok", 12)));   // 200 OK

// ASP.NET Core : app.Use(async (ctx, next) => { …; await next(); });

Chain of Responsibility en PHP

chain-of-responsibility.php 36 lignes
abstract class Handler
{
    private ?Handler $next = null;

    public function then(Handler $next): Handler
    {
        $this->next = $next;
        return $next;
    }

    public function handle(array $req): string
    {
        return $this->next?->handle($req) ?? '200 OK';
    }
}

class Auth extends Handler
{
    public function handle(array $req): string
    {
        return empty($req['token']) ? '401' : parent::handle($req);
    }
}

class RateLimit extends Handler
{
    public function handle(array $req): string
    {
        return ($req['rpm'] ?? 0) > 60 ? '429' : parent::handle($req);
    }
}

$chain = new Auth();
$chain->then(new RateLimit());
echo $chain->handle(['token' => 'x', 'rpm' => 12]); // 200 OK
// C'est exactement le principe du pipeline de middlewares Laravel

Chain of Responsibility en Go

chain-of-responsibility.go 20 lignes
type Middleware func(next http.Handler) http.Handler

func Auth(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("Authorization") == "" {
            http.Error(w, "unauthorized", http.StatusUnauthorized)
            return // la chaîne s'arrête ici
        }
        next.ServeHTTP(w, r) // sinon on passe au maillon suivant
    })
}

func Chain(h http.Handler, mws ...Middleware) http.Handler {
    for i := len(mws) - 1; i >= 0; i-- {
        h = mws[i](h)
    }
    return h
}

http.Handle("/api", Chain(controller, Auth, RateLimit, Validate))

Questions fréquentes

Qu'est-ce que le design pattern Chain of Responsibility ?

Faire passer une requête le long d'une chaîne de handlers : chacun la traite, l'arrête, ou la transmet au suivant. Transformer chaque vérification en handler autonome qui possède une référence vers le suivant. On assemble la chaîne librement ; chaque maillon décide de couper ou de continuer.

Quand utiliser le pattern Chain of Responsibility ?

Middlewares HTTP (Laravel, Express, ASP.NET, Go) ; Pipelines de validation / filtres ; Gestion d'événements (bubbling DOM).

Quels sont les avantages et les inconvénients du pattern Chain of Responsibility ?

Avantages : Ordre des traitements configurable ; Single Responsibility par maillon ; Ajout / retrait de maillons sans toucher aux autres. Limites : Une requête peut traverser la chaîne sans être traitée ; Débogage du flux moins direct.