
#include <iostream>
using namespace std;
//Handler
class Rescuer {
protected:
Rescuer* next = NULL;
int code;
virtual void toHelp() = 0;
public:
//HandleRequest()
void help(int code) {
if (this->code == code) {
toHelp();
} else if (next != NULL) {
next->help(code);
}
}
};
//ConcreteHandler
class Firefighter: public Rescuer {
public:
Firefighter(Rescuer* next) {
this->next = next;
this->code = 1;
}
protected:
void toHelp() {
cout << "call firefighters\n";
}
};
//ConcreteHandler
class Police: public Rescuer {
public:
Police(Rescuer* next) {
this->next = next;
this->code = 2;
}
protected:
void toHelp() {
cout << "call the police\n";
}
};
//ConcreteHandler
class Ambulance: public Rescuer {
public:
Ambulance(Rescuer* next) {
this->next = next;
this->code = 3;
}
protected:
void toHelp() {
cout << "call an ambulance\n";
}
};
Ambulance ambulance(NULL);
Police police(&ambulance);
Firefighter firefighter(&police);
firefighter.help(1);
//printed: call firefighters
firefighter.help(2);
//printed: call the police
firefighter.help(3);
//printed: call an ambulance
| Можно избежать жесткой зависимости отправителя запроса от его получателя, при этом запросом начинает обрабатываться один из нескольких объектов. Объекты-получатели связываются в цепочку, и запрос передается по цепочке, пока какой-то объект его не обработает. |