DEV Community

loading...

Chain of Responsibility Pattern

eidher profile image eidher ・2 min read

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.

Alt Text

Participants

  • Handler: defines an interface for handling the requests. (optional) implements the successor link
  • ConcreteHandler: handles requests it is responsible for. Can access its successor. If the ConcreteHandler can handle the request, it does so; otherwise, it forwards the request to its successor.
  • Client: initiates the request to a ConcreteHandler object on the chain.

Code

public class Main {

    public static void main(String[] args) {
        Handler h1 = new ConcreteHandler1();
        Handler h2 = new ConcreteHandler2();
        Handler h3 = new ConcreteHandler3();
        h1.setSuccessor(h2);
        h2.setSuccessor(h3);
        int[] requests = { 2, 5, 14, 22, 18, 3, 27, 20 };

        for (int request : requests) {
            h1.handleRequest(request);
        }

    }
}

public abstract class Handler {

    protected Handler successor;

    public void setSuccessor(Handler successor) {
        this.successor = successor;
    }

    abstract void handleRequest(int request);
}

public class ConcreteHandler1 extends Handler {

    @Override
    public void handleRequest(int request) {
        if (request >= 0 && request < 10) {
            System.out.println(this.getClass().getSimpleName() + " handled request " + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}

public class ConcreteHandler2 extends Handler {

    @Override
    public void handleRequest(int request) {
        if (request >= 10 && request < 20) {
            System.out.println(this.getClass().getSimpleName() + " handled request " + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}

public class ConcreteHandler3 extends Handler {

    @Override
    public void handleRequest(int request) {
        if (request >= 20 && request < 30) {
            System.out.println(this.getClass().getSimpleName() + " handled request " + request);
        } else if (successor != null) {
            successor.handleRequest(request);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

ConcreteHandler1 handled request 2
ConcreteHandler1 handled request 5
ConcreteHandler2 handled request 14
ConcreteHandler3 handled request 22
ConcreteHandler2 handled request 18
ConcreteHandler1 handled request 3
ConcreteHandler3 handled request 27
ConcreteHandler3 handled request 20
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide