中介者模式通过引入中介者对象集中管理多个同事类之间的交互,降低它们的直接耦合。在C++中,定义Mediator接口和Colleague基类,具体同事类如Button、TextBox、Label通过mediator通信;事件发生时通知中介者,由具体中介者DialogMediator协调行为,例如点击按钮时读取文本框内容并更新标签显示;所有组件初始化时注入中介者,实现松耦合。该模式适用于UI或游戏对象系统等多对象通信场景,需注意避免中介者过于臃肿,必要时拆分职责。

中介者模式用于降低多个对象之间的直接耦合,通过引入一个中介者对象来统一管理这些对象之间的交互。在C++中实现中介者模式,关键在于定义一组同事类(Colleague)和一个中介者接口(Mediator),让同事类只与中介者通信,而不是彼此直接调用。
中介者通常是一个抽象接口,声明了同事对象之间交互的方法。这样可以让具体中介者灵活实现逻辑。
class Mediator;
<p>class Colleague {
public:
virtual ~Colleague() = default;
void setMediator(Mediator<em> m) { mediator = m; }
protected:
Mediator</em> mediator = nullptr;
};</p><p>class Mediator {
public:
virtual ~Mediator() = default;
virtual void onEvent(Colleague* sender, const std::string& event) = 0;
};</p>每个同事类持有对中介者的引用,当发生事件时通知中介者,而不是直接操作其他对象。
class Button : public Colleague {
public:
void click() {
if (mediator) {
mediator->onEvent(this, "click");
}
}
};
<p>class TextBox : public Colleague {
public:
void setText(const std::string& text) {
this->text = text;
if (mediator) {
mediator->onEvent(this, "text_changed");
}
}
std::string getText() const { return text; }
private:
std::string text;
};</p><p>class Label : public Colleague {
public:
void display(const std::string& content) {
<strong>// 模拟显示更新</strong>
std::cout << "Label displays: " << content << std::endl;
}
};</p>具体中介者知道所有同事对象,并根据事件协调它们的行为。
立即学习“C++免费学习笔记(深入)”;
class DialogMediator : public Mediator {
public:
DialogMediator(Button* b, TextBox* t, Label* l)
: button(b), textBox(t), label(l) {
button->setMediator(this);
textBox->setMediator(this);
label->setMediator(this);
}
<pre class='brush:php;toolbar:false;'>void onEvent(Colleague* sender, const std::string& event) override {
if (sender == button && event == "click") {
std::string text = textBox->getText();
label->display("Hello, " + text);
}
else if (sender == textBox && event == "text_changed") {
<strong>// 可以在这里响应文本变化</strong>
}
}private: Button button; TextBox textBox; Label* label; };
将所有组件交给中介者管理,组件之间不再直接依赖。
int main() {
Button* btn = new Button;
TextBox* box = new TextBox;
Label* lbl = new Label;
<pre class='brush:php;toolbar:false;'>DialogMediator mediator(btn, box, lbl);
box->setText("World");
btn->click(); <strong>// 输出: Label displays: Hello, World</strong>
delete btn; delete box; delete lbl;
return 0;}
基本上就这些。中介者模式把原本分散的交互集中到一个地方,便于维护和扩展。尤其适合UI组件、游戏对象系统这类多对象频繁通信的场景。注意避免中介者变得过于庞大,必要时可拆分职责。
以上就是C++如何实现一个中介者模式_C++设计模式之用一个中介对象来封装一系列的对象交互的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号