π¦ Chain of Responsibility Pattern in Java — Step-by-Step Guide
The Chain of Responsibility (CoR) is a behavioral design pattern that allows a request to pass through a chain of handlers.
Each handler decides either to process the request or pass it to the next handler in the chain.
This pattern helps in decoupling senders and receivers — the sender doesn’t need to know which handler will eventually process the request.
π§ Concept
-
A chain is a series of objects (handlers) connected together.
-
Each handler knows only about the next handler in the chain.
-
When a request comes in:
-
The current handler checks if it can handle it.
-
If yes → it processes it.
-
If not → it forwards it to the next handler in the chain.
-
π Real-World Analogy — Parcel Delivery Service
Imagine a parcel service with branches in:
When a parcel is sent:
-
A Bangalore branch first receives it.
-
If the parcel is for Bombay, Bangalore forwards it to Bombay.
-
If it’s for Delhi, it goes from Bangalore → Bombay → Delhi.
Each branch only handles parcels for its location, and passes others onward.
That’s exactly how the Chain of Responsibility Pattern works!
⚙️ Implementation — Step by Step
π§© Step 1: Create the Chain Interface
This defines the contract for all handlers.
π§© Step 2: Create Handler — Bangalore
π§© Step 3: Create Handler — Bombay
π§© Step 4: Create Handler — Delhi
π§© Step 5: Create the Parcel Class
π§© Step 6: Set Up the Chain (Main Class)
π§Ύ Output
π§ How It Works (Step-by-Step Flow)
| Step | Action | Explanation |
|---|---|---|
| 1️⃣ | ParcelService sets up the chain | Bangalore → Bombay → Delhi |
| 2️⃣ | A request (parcel) starts at Bangalore | Bangalore checks if destination matches |
| 3️⃣ | If not, forwards to next handler | The parcel moves along the chain |
| 4️⃣ | Handler matches parcel destination | Processes it and stops the chain |
| 5️⃣ | If no handler matches | Request is ignored or logged |
π Benefits of Chain of Responsibility
-
✅ Loose coupling — Sender doesn’t need to know which handler will process the request
-
✅ Extensibility — Add new handlers easily without changing existing code
-
✅ Flexible processing — Handlers can process partially or pass along
-
✅ Separation of concerns — Each handler focuses on one specific job
⚠️ Things to Watch Out For
-
π« The chain must be properly linked (missing
setNextDestination()can break flow). -
⚙️ Handlers should ideally stop propagation once a request is processed.
-
π§© Avoid creating circular chains — can cause infinite loops.
π§© UML-Like Text Diagram
π¬ Real-World Applications
| Use Case | Example |
|---|---|
| Web request filtering | Servlet Filters in Java EE (FilterChain) |
| Logging framework | Different log handlers (Console, File, DB) |
| Event handling systems | UI event bubbling or middleware |
| Authorization pipelines | Request passes through validators or access checkers |
