Fundamentals 10 min read

Understanding the Chain of Responsibility Design Pattern with Java Examples

This article explains the Chain of Responsibility design pattern, its typical use cases, demonstrates a flawed nested‑if implementation for a multi‑level game, and then shows step‑by‑step refactorings—including an abstract handler, concrete handlers, and a factory‑based dynamic chain—using Java code examples.

Architecture Digest
Architecture Digest
Architecture Digest
Understanding the Chain of Responsibility Design Pattern with Java Examples

The article introduces the Chain of Responsibility pattern, a behavioral design pattern that passes a request along a chain of handlers until one can process it.

Typical usage scenarios include multi‑condition workflow decisions such as permission control, ERP approval processes, and the underlying implementation of Java servlet filters.

Anti‑pattern example : a simple game with three levels is implemented using deeply nested if statements, leading to repetitive and hard‑to‑maintain code.

if (firstScore >= 80) {
    if (secondScore >= 90) {
        if (thirdScore >= 95) {
            // ...
        }
    }
}

The article then presents a naive refactor where each level is represented by its own handler class, but each handler still contains a reference to the next specific handler, resulting in limited extensibility.

public class FirstPassHandler {
    public int handler() { /* ... */ }
}
public class SecondPassHandler {
    public int handler() { /* ... */ }
}
public class ThirdPassHandler {
    public int handler() { /* ... */ }
}

Improved refactor : an abstract handler class is introduced to define a common next reference and a handler() method, allowing concrete handlers to focus only on their own logic and delegate to the next handler when appropriate.

public abstract class AbstractHandler {
    protected AbstractHandler next;
    public void setNext(AbstractHandler next) { this.next = next; }
    public abstract int handler();
}

public class FirstPassHandler extends AbstractHandler {
    private int play() { return 80; }
    @Override
    public int handler() {
        System.out.println("第一关--->FirstPassHandler");
        int score = play();
        if (score >= 80 && next != null) {
            return next.handler();
        }
        return score;
    }
}
// Similar implementations for SecondPassHandler and ThirdPassHandler

Finally, the article demonstrates a factory‑based approach using an enum to configure the chain dynamically. The factory reads handler metadata, creates handler instances via reflection, and links them together at runtime.

public enum GatewayEnum {
    API_HANDLER(new GatewayEntity(1, "api接口限流", "com.example.ApiLimitGatewayHandler", null, 2)),
    BLACKLIST_HANDLER(new GatewayEntity(2, "黑名单拦截", "com.example.BlacklistGatewayHandler", 1, 3)),
    SESSION_HANDLER(new GatewayEntity(3, "用户会话拦截", "com.example.SessionGatewayHandler", 2, null));
    // ...
}

public class GatewayHandlerEnumFactory {
    private static GatewayDao gatewayDao = new GatewayImpl();
    public static GatewayHandler getFirstGatewayHandler() {
        GatewayEntity first = gatewayDao.getFirstGatewayEntity();
        GatewayHandler firstHandler = newGatewayHandler(first);
        // link subsequent handlers
        // ...
        return firstHandler;
    }
    private static GatewayHandler newGatewayHandler(GatewayEntity entity) {
        try {
            Class
clazz = Class.forName(entity.getConference());
            return (GatewayHandler) clazz.newInstance();
        } catch (Exception e) { e.printStackTrace(); }
        return null;
    }
}

The conclusion emphasizes that design patterns like the Chain of Responsibility are valuable tools for writing clean, maintainable code and encourages further study.

chain of responsibilityJavasoftware architecturedesign patternrefactoring
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.