中介者模式(Mediator Pattern)是一种行为型设计模式,旨在通过引入一个中介者对象,来解耦多个对象之间的交互关系。在中介者模式中,对象之间不直接相互通信,而是通过中介者进行通信。中介者模式促进了对象之间的松耦合,提高了系统的可维护性和可扩展性。
#include <iostream>
#include <string>
#include <vector>
// 前向声明
class Mediator;
// 同事抽象类
class Colleague {
protected:
* mediator;
Mediatorpublic:
(Mediator* mediator) : mediator(mediator) {}
Colleaguevirtual void sendMessage(const std::string& message) = 0;
virtual void receiveMessage(const std::string& message) = 0;
};
// 中介者抽象类
class Mediator {
public:
virtual void sendMessage(const std::string& message, Colleague* colleague) = 0;
};
// 具体中介者类
class ConcreteMediator : public Mediator {
private:
std::vector<Colleague*> colleagues;
public:
void addColleague(Colleague* colleague) {
.push_back(colleague);
colleagues}
void sendMessage(const std::string& message, Colleague* colleague) {
for (auto c : colleagues) {
if (c != colleague) {
->receiveMessage(message);
c}
}
}
};
// 具体同事类
class ConcreteColleague : public Colleague {
public:
(Mediator* mediator) : Colleague(mediator) {}
ConcreteColleaguevoid sendMessage(const std::string& message) {
->sendMessage(message, this);
mediator}
void receiveMessage(const std::string& message) {
std::cout << "Received message: " << message << std::endl;
}
};
int main() {
// 创建中介者和同事对象
;
ConcreteMediator mediator(&mediator);//在实际场景中,具体同事类大概率是不同的具体类型,只不过是Colleague的派生类
ConcreteColleague colleague1(&mediator);
ConcreteColleague colleague2// 将同事对象添加到中介者中
.addColleague(&colleague1);
mediator.addColleague(&colleague2);
mediator// 同事对象之间通过中介者进行通信
.sendMessage("Hello from colleague1!");
colleague1.sendMessage("Hi from colleague2!");
colleague2return 0;
}
/*
Received message: Hello from colleague1!
Received message: Hi from colleague2!
*/