Behavioral – Chain of Responsibility
August 24, 2020 2 min read

Chain of responsibility pattern is one of behavioral pattern that used to achieve loose coupling in software design where a request from client is passed to a chain of objects to process them. Then the object in the chain will decide themselves who will be processing the request and whether the request is required to be sent to the next object in the chain or not.
Let’s see the example of chain of responsibility pattern.

First I created a class “Currency” that store the amount to dispense and used by the chain implementations.
The base interface should have a method to define the next processor in the chain and the method that will process the request. Our ATM Dispense interface will look like below.

We need to create different processor classes that will implement the “DispenseChain” interface and provide implementation of dispense methods. Since we are developing our system to work with three types of currency bills – 50$, 20$ and 10$, we will create three concrete implementations.




Here the most important thing is the implementation of dispense method. You can see that every implementation is trying to process the request and based on the amount, it might process some or full part of it.
If one of the chain not able to process it fully, it sends the request to the next processor in chain to process the remaining request. If the processor is not able to process anything, it just forwards the same request to the next chain.
This is a very important step and we should create the chain carefully, otherwise a processor might not be getting any request at all. For example, in our implementation if we keep the first processor chain as “Dollar10Dispenser” and then “Dollar20Dispenser”, then the request will never be forwarded to the second processor and the chain will become useless.
Here is our ATM Dispenser implementation to process the user requested amount.

Output:

You can visit the below given articles to learn about creational design patterns and Structural Design Patterns.
Thank you.
Creational Design Patterns
Abstract Factory Design Pattern
Structural Design Patterns


