Skip to main content

How is a request passed along a chain of handlers?

Passing a request in the Chain of Responsibility pattern is organized through sequential delegation - each handler receives the request, decides whether it can handle it, and either performs the action or passes it on to the next link.


1. Basic Principle

Each handler stores a reference to the next one (nextHandler) and implements a handle(request) method:

java
abstract class Handler { protected Handler next; public Handler linkWith(Handler next) { this.next = next; return next; } public abstract boolean handle(String request); }

2. Handoff Mechanism

  1. The client sends the request to the first handler in the chain.
  2. The handler checks whether it can handle it.
  • If yes, it performs the action (and may stop the chain).
  • If no, it calls next.handle(request).
  1. The request travels along the chain until one of the handlers processes it or the chain ends.

3. Example

java
class AuthHandler extends Handler { public boolean handle(String request) { if (request.equals("auth")) { System.out.println("Checking authorization"); return true; // handled, the chain stops } if (next != null) return next.handle(request); return false; } } class LogHandler extends Handler { public boolean handle(String request) { System.out.println("Logging the request"); if (next != null) return next.handle(request); return false; } }

Building the chain:

java
Handler chain = new LogHandler(); chain.linkWith(new AuthHandler()); chain.handle("auth");

4. Key Traits

  • Flexibility: links can easily be reordered or added.
  • Transparency: the sender does not know exactly who will handle the request.
  • Control over handoff: the chain can end early (once handled successfully).

Summary

A request in the Chain of Responsibility pattern travels through a linear chain of objects, where each handler decides for itself whether to handle it or pass it on. This creates a flexible, configurable sequence of actions without rigid links between components.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.