這樣的協作機制允許我們將各個 Colleagues 的互動邏輯集中在 Mediator 中,從而達到減少系統耦合度和提高可維護性的目的
// Mediator Interface
class Mediator {
public:
virtual void notify(const std::string& message, const std::string& colleague) = 0;
};
// Concrete Colleague
class Colleague {
private:
Mediator* mediator;
std::string name;
public:
Colleague(Mediator* med, const std::string& n) : mediator(med), name(n) {}
void send(const std::string& message) {
mediator->notify(message, name);
}
};
// Concrete Mediator
class ConcreteMediator : public Mediator {
private:
std::vector<Colleague*> colleagues;
public:
void addColleague(Colleague* colleague) {
colleagues.push_back(colleague);
}
void notify(const std::string& message, const std::string& colleague) override {
std::cout << colleague << " says: " << message << std::endl;
}
};
int main() {
ConcreteMediator mediator;
Colleague alice(&mediator, "Alice");
Colleague bob(&mediator, "Bob");
mediator.addColleague(&alice);
mediator.addColleague(&bob);
alice.send("Hello, Bob!");
bob.send("Hi, Alice!");
}