Design Pattern (Part 05) — Chain Of Responsibility Pattern

Arun prashanth
3 min readMay 24, 2021

--

Photo by Google

Normally design patterns are given a solution for real-world problems. This pattern lets you pass requests along a chain of handlers. This comes under the behavioral design pattern. This pattern request from the client is passed to a chain of objects to process them. The chain in the object will decide who is processing the request and whether the request is required to be sent to the next object in the chain or not.

This will “avoid coupling the sender of a request to its receiver by giving multiple objects a chance to handle the request”.

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.

When to use Chain of Responsibility Design Pattern

  1. when decoupling a request’s sender and receiver.
  2. Multiple objects, determined at runtime, are candidates to handle a request.
  3. when don’t want to specify handlers explicitly in code.
  4. When more than one object can handle a request and the handler is unknown.

The main advantage of a chain of responsibility pattern is to reduce the coupling. Logger in Java API is a real-world example for the Chain of Responsibility Design Pattern implementation.

Real-world Example of Chain of Responsibility Design Pattern

In this Picture you can see four Handler in right side which are HundredRsHandler, FiftyRsHandler, TwentyRsHandler, FiveRsHandler. This HundredRsHandler used to dispatch 100Rs notes and FiftyRsHandler used to dispatch 50Rs notes like other Handler will dispatch the notes as well. There is an ATM it’s using these Handlers. left side you can see john he is a person. Suppose say John wants to withdraw 455Rs from the ATM. So he goes to the ATM and inserts his debit card. So ATM will ask for his unique password. So he enters the PIN number. If the PIN number is ok John should enter the amount which he going to withdraw. That is 455RS. Once he clicks to confirm the withdrawal request will go to the HundredRsHandler first. So Handler will calculate to dispatch 4*100 notes. So remaining 55Rs. Then it will send the 55Rs to the next Handler which is FiftyRsHandler. So this FiftyRsHandler does the calculation. It can give 1 fifty rupees note. After that, the remaining balance 5Rs move to the next Handler. Here the next Handler is TwentyRsHandler. So 5Rs can’t be dispatch by TwentyRsHandler so it's a move to the next Handler. Here FiveRsHandler will dispatch one 5Rs Note. So total 455Rs note will dispatch.

Class Diagram

If you want to get more clear about this with the Implementation code, please go through my Github Link which is shown below:

--

--

Arun prashanth
Arun prashanth

Written by Arun prashanth

Software Engineer at Virtusa (Pvt) Ltd.

No responses yet