中介者模式通过引入中介者对象统一管理多个对象间的交互,降低它们之间的直接依赖。在C++中,它适用于多个对象频繁交互导致紧耦合的场景,如GUI组件通信。示例中Button和TextBox不直接调用彼此,而是通过DialogMediator转发消息,实现解耦。notify方法根据事件类型处理逻辑,如点击按钮触发提交或文本变化触发验证。优点包括减少类间依赖、提升可维护性,但中介者可能因集中过多逻辑而变得臃肿,需合理设计。结合智能指针可避免内存泄漏。该模式广泛应用于需要集中控制交互的系统。

中介者模式用来降低多个对象之间复杂的直接依赖关系。在C++中,当一组对象交互频繁且逻辑分散,代码会变得难以维护。通过引入一个“中介者”对象来统一处理这些交互,可以让原本紧耦合的对象彼此独立,提升可扩展性和可测试性。
中介者模式属于行为型设计模式,它的核心思想是:将对象之间的通信封装到一个中介者对象中。对象不再相互引用,而是通过中介者进行消息传递。这样,对象只需知道中介者,而不需要了解其他协作对象的细节。
适用于以下场景:
定义中介者接口和同事类基类,再由具体类实现细节。下面是一个简化示例:
立即学习“C++免费学习笔记(深入)”;
// Mediator.h
#include <iostream>
#include <string>
class Colleague;
class Mediator {
public:
virtual ~Mediator() = default;
virtual void notify(Colleague* sender, const std::string& event) = 0;
};
class Colleague {
protected:
Mediator* mediator;
public:
Colleague(Mediator* m) : mediator(m) {}
virtual ~Colleague() = default;
};
// 具体同事类
class Button : public Colleague {
public:
Button(Mediator* m) : Colleague(m) {}
void click() {
std::cout << "Button clicked\n";
mediator->notify(this, "click");
}
};
class TextBox : public Colleague {
private:
std::string text;
public:
TextBox(Mediator* m) : Colleague(m), text("") {}
void setText(const std::string& t) {
text = t;
std::cout << "TextBox set to: " << text << "\n";
mediator->notify(this, "text_changed");
}
const std::string& getText() const { return text; }
};
class DialogMediator : public Mediator {
private:
Button* button;
TextBox* textbox;
public:
DialogMediator(Button* b, TextBox* t) : button(b), textbox(t) {}
void notify(Colleague* sender, const std::string& event) override {
if (sender == button && event == "click") {
if (textbox->getText().empty()) {
std::cout << "Cannot submit: text is empty\n";
} else {
std::cout << "Submitting: " << textbox->getText() << "\n";
}
} else if (sender == textbox && event == "text_changed") {
std::cout << "Validation triggered.\n";
}
}
};
在main函数中组合对象并测试交互:
int main() {
Button* btn = new Button(nullptr);
TextBox* box = new TextBox(nullptr);
DialogMediator* dlg = new DialogMediator(btn, box);
btn->mediator = dlg;
box->mediator = dlg;
box->setText("Hello");
btn->click();
// cleanup
delete btn;
delete box;
delete dlg;
return 0;
}
输出结果:
TextBox set to: Hello
Validation triggered.
Button clicked
Submitting: Hello
使用中介者模式的好处:
需要注意的问题:
基本上就这些。中介者模式在GUI系统、游戏对象管理、模块间通信中非常实用。关键是把交互逻辑从对象中剥离出来,交给中介者统一调度。C++中结合虚函数和指针可以灵活实现,同时注意资源管理和接口清晰性。不复杂但容易忽略。
以上就是C++怎么实现一个中介者设计模式_C++行为型模式与对象解耦的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号