Chain of Responsibility Design Pattern

Thilini Weerasinghe
5 min readJun 9, 2021

--

Source: https://www.vinsguru.com/

This is very interesting design pattern that coming under the behavioral design patterns. Think you have to manage tasks based on the different user levels and in the top level users they have all access and when comes to lower level it reduces accessibility as a hierarchy. When you thinks to develop that it seems very complex task. But don’t be confused. There is a design pattern for managed such type of scenarios easily and it is called as Chain of Responsibility pattern. So, this article describes about chain of responsibility and how we can implement such kind of pattern based on the real world scenario.

The main use of this pattern is it enables loosely coupling with the entities. As an example think that sender is don’t know about who is the receiver and receiver also don’t aware about the sender. What it does is encouraged them to perform their jobs without worrying about other party. So it decoupled sender and receiever. The most important feature in this design pattern after the deployment of the project, then you want to change the order of receiver r sender, then you can make it successfully without changing the core implementation. So it makes easy in making changes. Simply as it reveals in its name it has capability to pass the requests along the chain of handler.Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain. See the following image and then you can understand it concept.

Source: https://refactoring.guru/

Advantages 👍

  • Easy to manage the request handling order
  • Easy to add new handler to the system, without breaking core implementation
  • It follows single responsibility principle. A class needs to take care about its operation only as it decouple from others

Disadvantages 👎

  • There can be unhandled requests available
  • End user can manipulate the chain

Applications 📔

Here are some specifications about its applications

  • It is suitable if you want to decouple sender and receiver
  • When the developers don’t want to specify the receiver in their code(receiver is unknown)
  • When you want to send a request to multiple objects without explicitly mention the receiver
  • Using Loggers in the software development and customer care support or technical supporting via call are some good example that can this pattern.

Digram Representation 📝

See the following graph nd you can get clear understanding about the process

Class diagram for the Chain of Responsibility Pattern. Source: https://reactiveprogramming.io/
Sequence Diagram for the Chain of Responsibility pattern. Source:https://reactiveprogramming.io/

Above diagram represents how the handlers manage the process between sender and receiver.

This design pattern has some relationship with other patterns. It is often used in the Composite pattern as conjunction. In this example, when a leaf component receives a request, it may transmit it down the object tree’s chain of parent components to the root. Further it can be develop to execute different operations in the same context as Commands. Class structure of the pattern is as same as the Decortor design pattern and both of them are rely on recursive composition.

Implementation 💻

Use Case: Let’s get the general process of the ATM machine. For the every valid withdrwal amount it provides currency papers as the output. In these output currency,it doesn’t provides currency paper relatated to one category. It always try to give mix of 100, 500, 1000, and 5000 paper currency. So now you have to design a system to handle these tasks. Following are the some constraints you should care while you developing the system.

  • Minimum amount can requested from the ATM machine is Rs.100
  • Maximum amount can requesting from the ATM is Rs.100000 in one day
  • Requested amount always should be multiple of 100

Let’s design a system to output the currency dispenser process using chain of responsible pattern.

  • First of all lets create a class to hold the amount that need to withdarw from the ATM machine.
  • Then we have to create a handler abstract class to handle the process. Purpose of creating this handler class is to manage the dispense value for particluar amount and move for another class to match for the dispense value
  • Next step is to do the calculations to get the particular curency paper type. Therefore we have to create four different class for the four types of currency paper values.(5000, 1000, 500, 100). Here I have included a code snippets for one class and you should create four classes and change the logic
  • Next step is very important. Now we are going to create a class to handle the money withdrawal process as a chain. Here we are ordering the paper value from higher value to lower value and then put the higher value class instance to the chain
  • As the final step, we have to create a main application to get user input about the amount. Here we create a method to check the validity of the amount as the constraints mentioned in the use case scenario

So let’s run the program and enter the 7800 as the withdrawal amount and lets see the output.

Please enter amount to withdraw (multiple of 100, max 100000 ):7800Dispensing '1' Rs.5000 currency notes.Dispensing '2' Rs.1000 currency notes.Dispensing '1' Rs.500 currency notes.Dispensing '3' Rs.100 currency notes.

So let’s see that 500 currency papers are finished in the system and now what we have to do is doing small chainge in the ATMWithdrawal.java class . Here is the change.

CHANGE >>> 
thousandDispender.setNextDispender(fiveHundredDispender);
INTO>>>>
thousandDispender.setNextDispender(hundredDispender);

Do the change and run the program again. Let’s see the output after the change.

Please enter amount to withdraw (multiple of 100, max 100000 ):7800Dispensing '1' Rs.5000 currency notes.Dispensing '2' Rs.1000 currency notes.Dispensing '8' Rs.100 currency notes.

Now you can see that output has changed. I think now you can understand how easy this pattern to manage the receivers. We only do the simple modification in the chain and do not change the core implementation of the application.

I think now you have clear idea about the chain of responsibility pattern, it inherited advantages and disadvantages and its application. If you want to find the full code impementation, click here.

Stay Safe & Learn New Things!!! 😃

--

--

Thilini Weerasinghe
Thilini Weerasinghe

Written by Thilini Weerasinghe

Currently working as an Associate Software Engineer at Virtusa. Has completed degree in B.Sc (Hons) Computing & Information Systems. After all I am a Human...