Nerd For Tech
Published in

Nerd For Tech

Chain of Responsibility Design Pattern

Definition

Chain of Responsibility Pattern is a Design pattern that forms sequentially connected components and consumers can simply pass the object to the first component. Then that particular object gets processed by each component according to the constructed sequence.

This pattern falls under the category of behavioral Design patterns. In simple terms, this pattern lets the application pass requests along a chain of handlers. Each handler can decide either to process the request or to pass it to the next handler in the constructed sequence. This pattern is mainly used to introduce loose coupling to the application. It basically decouples the sender and receiver of a particular request based on the type.

Usage

  • When the program processes different kinds of requests in various ways but sequences are unknown beforehand.
  • When there is a requirement to execute several handlers in a particular order.
  • When the sequence of handlers changes at runtime.

Pros and Cons

Pros

  • Possibility to control the order of request handling.
  • Introduce new handlers into the application without breaking the existing code.
  • Decoupling of classes(Operations invoking and performing.

Cons

  • Possibility of having unhandled requests.
  • Possibility of the end-user to manipulate the application.

Chain of Responsibility Design Pattern In the Context of Javascript

Let’s try to further understand this pattern with the help of a real-world example.

Use Case

“New City Medicals” is a famous Pharmacy Chain Located in Sri Lanka. This chain delivers medical supplies to thousands of users on a daily basis. Their stores are located in all the major cities around the country.

The order process

The pharmacist will first look for a particular item in its Front Inventory. If the item is not available, the search will be continued to the back Inventory. If the item is not available in that location, the search will be passed to the distributor warehouse which is located per region. The next and final place to look is the central warehouse located in Colombo.

Requirement: The Pharmacy needs an application for Pharmacists to easily find the location of a particular medicine with the quantity.

Note: For the sake of simplicity, we will use a Local JSON file as the database.

Now Let’s try to implement a solution.

Initial Implementation without the pattern

The Database —

The Pharmacy —

Index file —

Output —

Fig 1: Initial Implementation without Pattern

In this implementation, we need to pass the Inventory location each time. The search is only based upon the particular inventory. This is not very efficient. Let’s implement the Chain of Responsibility Pattern and make the search forward to the relevant inventories in the available sequence.

Implementation of Chain of Responsibility Design Pattern

Step 01: Change the index.js class and pass the entire inventory.

Index file —

Step 02:

Now let’s implement a new class called Storage. This class is Responsible for looping through the dataset and finding the item and returning it back.

Storage class —

Important Points

  • SearchInventory(ItemName) — Loop through the actual dataset for the Medicine.
  • .setNext() — Set the next inventory to the next Storage.
  • .find() — Check if we have actually found it. If it is there, the details of the medicine will be returned. Otherwise, it will return a string value to say that the medicine is not available.
  • “else if(this.next)” in line 29 — If the “this.next” available we need to loop through again in the next Inventory.

Step 03 :

Now we can implement the Pharmacy Class. First, we are going to create variables for each Inventory with the help of the Storage class.

Pharmacy Class —

Important Points

  • this.storage = frontInventory — The starting point is the front Inventory.
  • Then we perform the chaining with the help of “.setNext()” method.

Output

Fig 2: Final Implementation

Process

The system first checks for the “Syrup10” in the front Inventory. It's not available there. Therefore the application moves to the Back inventory and checks for availability. It's not available in the back Inventory as well. Then again the system moves to the Distribution center and check. “Syrup10" is not available in the Distribution center as well. Finally the application checks for the medicine in the central inventory. “Syrup10” is available in that location. Therefore application returns the availability with the quantity and available location.

Now we can see that we have successfully implemented the solution with the help of the Chain of Responsibility Design Pattern. The pharmacist and enter the Medicine he/she wants and the system will generate the availability of it with the available location.

The following URL provides the complete source code for the above implementation.

I have used the following playlist by Mr.Krishntha Dinesh to gather the required information.

--

--

--

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Recommended from Medium

Adding a Stripe Payment Component (explained and made easy)

It’s time to get over mongoose for your Node application

Is React Good For SEO?

‘this’ in JavaScript

5 Simple Rules to Master ‘this’ in JavaScript

Authenticated Testing with Mocha and Chai

React App Building, A HANDY GUIDE

How to get the most out of the JavaScript console

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Damsak Bandara

Damsak Bandara

Associate Software Engineer at Virtusa

More from Medium

A tale on Software design

Automating Your Code Quality — Considerations and Innovation

SOLID Design Principles

Testing Software Systems