定义:中介者模式(Mediator Pattern)是一种行为设计模式,用于松散地耦合一组对象,使它们通过中介者对象进行通信,而不是直接相互引用。这有助于减少对象之间的依赖性和复杂性,同时提高代码的可维护性和可扩展性。
与观察者模式的对比:
相同点:两者都属于行为型设计模式,关注对象之间的交互和通信。通过引入中介者或观察者机制,使得对象之间的交互更加清晰和可控。
不同点:观察者模式是被观察者发生变化通知每个观察者,核心觉得是被观察者和观察者。但中介模式的核心是中介者,它负责协调和控制一组对象之间的交互,一个对象发生变化或进行操作时,中介者负责将变化或操作传到给其他对象。
代码:
// 抽象中介者
class Mediator {
public: virtual ~Mediator() = default; virtual void send(const std::string& from, const std::string& message) = 0;
}; // 抽象同事类
class Colleague {
protected: std::shared_ptr<Mediator> mediator; public: Colleague(std::shared_ptr<Mediator> mediator) : mediator(mediator) {} virtual ~Colleague() = default; virtual void receive(const std::string& from, const std::string& message) = 0; void sendMessage(const std::string& message) { mediator->send(getName(), message); } virtual std::string getName() const = 0;
}; // 具体中介者(聊天室)
class ChatRoom : public Mediator { std::vector<std::shared_ptr<Colleague>> colleagues; public: void registerColleague(std::shared_ptr<Colleague> colleague) { colleagues.push_back(colleague); } void send(const std::string& from, const std::string& message) override { for (const auto& colleague : colleagues) { if (colleague->getName() != from) { colleague->receive(from, message); } } }
}; // 具体同事类(用户)
class User : public Colleague { std::string name; public: User(const std::string& name, std::shared_ptr<Mediator> mediator) : Colleague(mediator), name(name) {} void receive(const std::string& from, const std::string& message) override { std::cout << name << " received message from " << from << ": " << message << std::endl; } std::string getName() const override { return name; }
}; int main() { auto chatRoom = std::make_shared<ChatRoom>(); auto user1 = std::make_shared<User>("Alice", chatRoom); auto user2 = std::make_shared<User>("Bob", chatRoom); auto user3 = std::make_shared<User>("Charlie", chatRoom); chatRoom->registerColleague(user1); chatRoom->registerColleague(user2); chatRoom->registerColleague(user3); user1->sendMessage("Hello Bob and Charlie!"); user2->sendMessage("Hi Alice, how are you?"); user3->sendMessage("Good morning everyone!"); return 0;
}