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 until one handles it. Use when more than one object may handle a request and the handler is not known a priori, or when you want to issue a request to one of several objects without specifying the receiver explicitly.
Examples:
- An online ordering system runs incoming requests through a chain: authentication check → input sanitization → brute-force detection → cache lookup → actual order handler. Each check is a standalone handler that either stops and processes the request or passes it on — adding a new check means inserting one handler into the chain without touching the others.
class Handler {
public:
Handler* successor;
virtual void HandleRequest(Request* r) {
if (successor) successor->HandleRequest(r);
}
};
class ConcreteHandler : public Handler {
void HandleRequest(Request* r) override {
if (canHandle(r)) { /* handle */ }
else Handler::HandleRequest(r);
}
};
Synonyms: cor, chain of command