Chain of Responsibility Pattern

Chain of Responsibility Pattern

Consider that you need an allowance for your team and for that you need to take budget approval from your manager, manager's manager, manager's manager's manager ... all the way up till the CEO. Now anyone along the chain can either reject the claim or approve it and pass it to the next person for approval.

This is exactly what happens in the chain of responsibility pattern where you pass request along a chain of handlers. Each handler can process the request and pass it to the next one or reject the request and the chain breaks. Let's now look into the code.

No alt text provided for this image

Handler interface defines the methods our handlers would perform. Here we have also created a Base Class BaseHandler that extends the Handler Interface. This is done to avoid creating the boilerplate code in all the handlers. Next we make our Managers (handlers) extend this BaseHandler class. Inside the client we ask the first handler to process the request which then passes it to the next handler after the due processing. This is how the Chain of Responsibility Pattern is implemented.

I hope you liked this article. I regularly write such short fun articles on good coding practices. Follow Prateek Mishra and learn something new every week.

I took help from the following sources while writing this article:

  1. https://refactoring.guru/design-patterns/chain-of-responsibility
  2. https://www.geeksforgeeks.org/chain-responsibility-design-pattern/
  3. https://stackoverflow.com/questions/3721256/design-patterns-chain-of-resposibility-vs-decorator

Subhahu Jain

MTS @ Salesforce | Ex-SDE @ Amazon | LLDcoding.com | 500+ sessions on PrePlaced | 100K+ Mnth Page Views | Google Summer of Code Mentor | Top Mentor @ PrePlaced | Ex-SDE @ Hyland | TA at Relevel | GCI Mentor | Freelancer

8 个月
回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了