JavaOmnibus
GoF Chain of Responsibility
GoF pattern • Behavioral
GoFBehavioralJava example

Chain of Responsibility solves a specific structural problem in the design.

Pass a request through handlers until one processes it.

Pattern overview

GoF pattern

Pass a request through handlers until one processes it.

Intent

Avoid coupling a sender to a single receiver by letting multiple handlers try to process a request.

Problem

Request handling rules vary, and hard-coded if/else dispatch becomes messy or brittle.

Solution

Link handlers together so each one can handle, transform, or pass the request onward.

Fit and tradeoffs

FamilyGoF
CategoryBehavioral
Best used when
  • For validation pipelines, middleware, and approval flows.
  • When rules should be composable and reorderable.
Tradeoffs
  • Request flow can become harder to trace.
  • Unclear ownership if too many handlers overlap.

Java example

This example is intentionally compact so the pattern shape stays easy to see.

interface Handler {
    void handle(Request request);
}

abstract class AbstractHandler implements Handler {
    private Handler next;

    public AbstractHandler next(Handler next) {
        this.next = next;
        return this;
    }

    protected void forward(Request request) {
        if (next != null) next.handle(request);
    }
}

final class AuthHandler extends AbstractHandler {
    public void handle(Request request) {
        if (!request.authenticated()) throw new SecurityException("Not authenticated");
        forward(request);
    }
}

Related pages

Keep exploring