Chain of Responsibility Pattern
Prateek Mishra
Software Engineer at Google | ex. Microsoft, Walmart | Gold Medalist, IIIT Allahabad | XAT'24: 99.8
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.
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:
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 个月https://lldcoding.com