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

中介者模式用来降低多个对象之间复杂的直接依赖关系。在C++中,当一组对象交互频繁且逻辑分散,代码会变得难以维护。通过引入一个“中介者”对象来统一处理这些交互,可以让原本紧耦合的对象彼此独立,提升可扩展性和可测试性。
什么是中介者模式
中介者模式属于行为型设计模式,它的核心思想是:将对象之间的通信封装到一个中介者对象中。对象不再相互引用,而是通过中介者进行消息传递。这样,对象只需知道中介者,而不需要了解其他协作对象的细节。
适用于以下场景:
- 多个对象之间存在复杂的调用关系,形成网状结构
- 对象修改影响范围大,牵一发而动全身
- 希望将交互逻辑集中管理,便于调试和扩展
基本结构与C++实现
定义中介者接口和同事类基类,再由具体类实现细节。下面是一个简化示例:
立即学习“C++免费学习笔记(深入)”;
// Mediator.h
#include iostream>
#include
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
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
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
} else {
std::cout getText()
}
} else if (sender == textbox && event == "text_changed") {
std::cout red.\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++中结合虚函数和指针可以灵活实现,同时注意资源管理和接口清晰性。不复杂但容易忽略。









