Used in interrupt handling, event pipelines, middleware, and packet processing.
- Decouples sender from receiver chain
- Flexible processing pipelines
C Example
#include <stdio.h>
void handlerA(int req) {
if(req < 10) printf("Handled by A\n");
}
void handlerB(int req) {
if(req >= 10) printf("Handled by B\n");
}
int main() {
int request = 15;
handlerA(request);
handlerB(request);
}
C++ Example
#include <iostream>
using namespace std;
class Handler {
protected:
Handler* next = nullptr;
public:
void setNext(Handler* n){ next = n; }
virtual void handle(int req){
if(next) next->handle(req);
}
};
class SmallHandler : public Handler {
public:
void handle(int req) override {
if(req < 10) cout<<"Small handled\n";
else Handler::handle(req);
}
};
class LargeHandler : public Handler {
public:
void handle(int req) override {
if(req >= 10) cout<<"Large handled\n";
}
};
int main() {
SmallHandler s; LargeHandler l;
s.setNext(&l);
s.handle(15);
}