Chain of responsibility design pattern

Introduction

In this article, we will talk about Chain Of responsibility design pattern. When we should use this design pattern and how you can implement it.

Type

Behavioral design pattern

Description

“Chain of responsibility” name itself suggests that there is a chain of something who will handle responsibility. Yes, we are giving an opportunity to more than one object to handle request by linking receiving object together.

GoF defines Chain of responsibility pattern as “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.”

So you can consider it as pipeline where each pipe will be considered as an object. Request will be passed through this series of objects from first to last. Each object will try to handle the request (try to satisfy some specific condition) and if current object cannot handle the request, then request will be passed to next chained object. So, We can ensure that our request will be handled by one of the object. In case, if our request won’t be handled by any of the object, then need to return null or need to throw an exception based on requirement.

UML Diagram

uml

Example

Lets say we have bank loan application. A customer can request for a loan. Loan can be of Home type or Business type.  If loan type is home and requested amount is less than 10 Lakh then that request  will be handled by Executive. If loan type is home and requested amount is bigger than 10 Lakh than that request will be handled by Senior Executive and If loan type is Business then that request will be handled by Branch Manager.

loanapprover
LoanApprover.cs
executive
Executive.Cs
seniorexecutive
SeniorExecutive.cs
branchmanager
BranchManager.cs
loanrequest
LoanRequest.cs
loantype
LoanType.cs
client
Client
output
Output

Class diagram

classdiagram1
Class diagram

When to use this design pattern:

  1. Multiple object can handle the request. It does not matter to caller which object will handle my request.
  2. Request won’t be handled is an acceptable outcome.

Leave a Reply

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