Chain of Responsibility is a behavioral design pattern that lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process the request or to pass it to the next handler in the chain.
Use Case
When we have sequential processing of requests/Checks that can be handled by different handlers.
Something like UI when Button -> Panel -> Window -> Application. Each of them can handle the event or pass it to the next one.
Code
Assume that we are building software ticket management system. We have different levels of support: Low, Medium, and High. Each level can handle certain types of tickets, and if a ticket cannot be handled at the current level, it is passed to the next level.
//Object data classpublicclassTicket{publicstringTitle{get;set;}publicstringDescription{get;set;}publicstringStatus{get;set;}publicstringPriority{get;set;}publicstringAssignedTo{get;set;}}
privatestaticvoidMain(){//Ticket management system with chainvarlowPriorityHandler=newLowPriorityHandler();varmediumPriorityHandler=newMediumPriorityHandler();varhighPriorityHandler=newHighPriorityHandler();lowPriorityHandler.SetNext(mediumPriorityHandler);mediumPriorityHandler.SetNext(highPriorityHandler);varticket1=newTicket{Title="Low priority issue",Description="This is a low priority issue.",Status="Open",Priority="Low",AssignedTo="John"};varticket2=newTicket{Title="Medium priority issue",Description="This is a medium priority issue.",Status="Open",Priority="Medium",AssignedTo="Jane"};varticket3=newTicket{Title="High priority issue",Description="This is a high priority issue.",Status="Open",Priority="High",AssignedTo="Bob"};lowPriorityHandler.Handle(ticket1);lowPriorityHandler.Handle(ticket2);lowPriorityHandler.Handle(ticket3);}