Chain of Responsibility Design Pattern in Java

By | July 5, 2020

In this post, We will talk and learn about the Chain of Responsibility Design Pattern in Java

Key Points About Chain of Responsibility Design Pattern :

  • The chain of responsibility design pattern falls under behavioral design pattern.
  • The chain of responsibility design pattern is mainly used to gain loose coupling in software design where a request from the client is passed to a chain of objects to process the request. Then the object in the chain has to decide who will be processing the request and whether the request is required to be sent to the next object in the chain or not.
  • The client does not know which Object in the chain will be processing the request and it will send the request to the first object in the chain.
  • Every object in the chain will have its own implementation to process the request, either complete or partial, or to send it to the next object in the chain.
  • Every object in the chain should have reference to the next object in the chain to forward the request to, it is achieved by java composition.
  • We should be careful while creating the chain otherwise there might be a case that the request will never be forwarded to a particular processor or there are no objects in the chain that are able to handle the request.

Chain of Responsibility Pattern in JDK:

Now Let’s move towards the implementation of the Chain of ResponsibilityDesign Pattern.

Here I am going to implement blow Use Case :

  • One of the great examples of the Chain of Responsibility pattern is the ATM machine.
  •  The user enters the amount to be dispensed and the machine dispense amount in terms of defined currency Notes such as Rs 2000, Rs 500, Rs 200 and Rs 100

Below is the complete source code:

Chain of Responsibility Design Pattern

MoneyDispenseChain.java

 

Currency.java

 

Rupees100DispenseChain.java

 

Rupees200DispenseChain.java

 

Rupees500DispenseChain.java

 

Rupees2000DispenseChain.java

 

ATMMachineDispenseChain.java

 

ClientTest.java

Few Input & Output of this client Program:

Please enter amout to despense:
15200
Depensing 7 Notes of Rs 2000
Depensing 2 Notes of Rs 500
Depensing 1 Notes of Rs 200
Please enter amout to despense:
6700
Depensing 3 Notes of Rs 2000
Depensing 1 Notes of Rs 500
Depensing 1 Notes of Rs 200
Please enter amout to despense:
450
Amount should be multiple of Rs 100

You May Also Like:

Singleton Design Pattern in java
Prototype Pattern in Java
Factory Pattern in Java
Abstract Factory Pattern in Java
Builder Pattern in Java
Adapter Design Pattern in Java
Decorator Design Pattern in Java
Facade Design Pattern in Java
Bridge Design Pattern in Java.

That’s all about the Chain of Responsibility Design Pattern in Java.
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *