Home / Design Pattern / Behavioral / Chain of Responsibility

Chain of Responsibility Design Pattern in Java

A request moves along a chain of handlers. Each handler either handles it or passes it to the next one.

Real life example

A leave request goes to the manager first. If the manager cannot approve, it goes to the director.

When to use

More than one object can handle a request and you do not know which one in advance.

Complete Java example

Save this as Main.java, then run javac Main.java and java Main.

public class Main {
    public static void main(String[] args) {
        Handler m = new Manager();
        m.setNext(new Director());
        m.handle(500);      // Manager approved
        m.handle(5000);     // Director approved
        m.handle(50000);    // Rejected
    }
}

abstract class Handler {
    private Handler next;
    Handler setNext(Handler n) { next = n; return n; }
    void handle(int amount) {
        if (next != null) next.handle(amount);      // pass forward
        else System.out.println("Rejected");
    }
}
class Manager extends Handler {
    void handle(int a) { if (a <= 1000) System.out.println("Manager approved"); else super.handle(a); }
}
class Director extends Handler {
    void handle(int a) { if (a <= 10000) System.out.println("Director approved"); else super.handle(a); }
}

Output

Manager approved
Director approved
Rejected