The Chain of Responsibility pattern is a behavioral design pattern that passes a request along a chain of handler objects until one of them handles it. Each handler decides either to process the request or forward it to the next handler in the chain.
Key Points: • Handlers share a common interface, typically with a handle() method and a reference to the next handler. • The sender of the request doesn't know which handler will ultimately process it, decoupling sender and receiver. • Handlers can be added, removed, or reordered without changing client code. • If no handler processes the request, it can fall through to a default behavior or be dropped. • It's commonly used for request pipelines like logging, validation, or approval workflows.
Example: In an expense approval system, a request might first go to a team lead, then a manager, then a director, with each handler approving amounts up to their limit and forwarding anything higher up the chain.
Interview Tip: A concise interview answer is:
"Chain of Responsibility passes a request through a chain of handler objects, each deciding to process it or pass it along, which decouples the sender from knowing exactly who will handle the request and makes the handling logic easy to extend or reorder."