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

中介者模式用于降低多个对象之间的直接耦合,通过引入一个中介者对象来统一管理这些对象之间的交互。在C++中实现中介者模式,关键在于定义一组同事类(Colleague)和一个中介者接口(Mediator),让同事类只与中介者通信,而不是彼此直接调用。
定义中介者接口
中介者通常是一个抽象接口,声明了同事对象之间交互的方法。这样可以让具体中介者灵活实现逻辑。
class Mediator;class Colleague {public:virtual ~Colleague() = default;void setMediator(Mediator m) { mediator = m; }protected:Mediator mediator = nullptr;};
class Mediator {public:virtual ~Mediator() = default;virtual void onEvent(Colleague* sender, const std::string& event) = 0;};
实现具体同事类
每个同事类持有对中介者的引用,当发生事件时通知中介者,而不是直接操作其他对象。
class Button : public Colleague {public: void click() { if (mediator) { mediator->onEvent(this, "click"); } }};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;};
class Label : public Colleague {public:void display(const std::string& content) {// 模拟显示更新std::cout << "Label displays: " << content << std::endl;}};
实现具体中介者
具体中介者知道所有同事对象,并根据事件协调它们的行为。
立即学习“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); }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") { // 可以在这里响应文本变化 }}
private:Button button;TextBox textBox;Label* label;};
使用示例
将所有组件交给中介者管理,组件之间不再直接依赖。
int main() { Button* btn = new Button; TextBox* box = new TextBox; Label* lbl = new Label;DialogMediator mediator(btn, box, lbl);box->setText("World");btn->click(); // 输出: Label displays: Hello, Worlddelete btn; delete box; delete lbl;return 0;
}
基本上就这些。中介者模式把原本分散的交互集中到一个地方,便于维护和扩展。尤其适合UI组件、游戏对象系统这类多对象频繁通信的场景。注意避免中介者变得过于庞大,必要时可拆分职责。
以上就是C++如何实现一个中介者模式_C++设计模式之用一个中介对象来封装一系列的对象交互的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1487568.html
微信扫一扫
支付宝扫一扫