【设计模式】中介者模式

概念

行为模式


类图


代码

cpp 复制代码
#include <iostream>

using namespace std;

class Component;
class Mediator {
public:
    virtual void Notify(Component* sender, const string& event) = 0;
};

class Component {
public:
    explicit Component(Mediator* mediator) {
        dialog = mediator;
    }

    void Click() {
        dialog->Notify(this, "click");
    }

    void KeyPress() {
        dialog->Notify(this, "keypress");
    }

protected:
    Mediator* dialog;
};

class Button : public Component {

};

class Textbox : public Component {

};

class Checkbox : public Component {
public:
    explicit Checkbox(Mediator* mediator) : Component(mediator) {};

    void Check() {
        dialog->Notify(this, "check");
    }
};

class AuthenticationDialog : public Mediator {
public:
    explicit AuthenticationDialog(const string& dialog) {
        title = dialog;
    }

    void Notify(Component* sender, const string& event) override {
        cout << "Auth " << event << endl;
    }

private:
    string title;
    // Checkbox* loginOrRegisterCheckbox;
    // Textbox* loginUserName, loginPassword;
    // Textbox* registrationUsername, registrationPassword, registrationEmail;
    // Button* okButton, cancelButton;
};

int main(int argc, char *argv[]) {
    auto auth = new AuthenticationDialog("OnBoarding");
    auto checkbox = new Checkbox(auth);

    auth->Notify(checkbox, "notify");
    checkbox->Check();

    delete checkbox;
    delete auth;

    return 0;
}
相关推荐
玫瑰花店35 分钟前
SomeIP报文详解
c++·someip
LengineerC41 分钟前
Rust仿node事件总线的简单实现
设计模式·rust
利刃大大1 小时前
【c++中间件】redis介绍 && redis-plus-plus库使用
c++·redis·中间件
永不停转1 小时前
关于 QGraphicsItemGroup 内部项目发生变化后group重新定位的问题
c++·qt
IT永勇2 小时前
C++设计模式-装饰器模式
c++·设计模式·装饰器模式
Murphy_lx2 小时前
std_ofstream
c++
草莓熊Lotso2 小时前
红黑树从入门到进阶:4 条规则如何筑牢 O (logN) 效率根基?
服务器·开发语言·c++·人工智能·经验分享·笔记·后端
啊董dong2 小时前
课后作业-2025年11月23号作业
数据结构·c++·算法·深度优先·noi
带鱼吃猫3 小时前
Linux系统:策略模式实现自定义日志功能
linux·c++
zzzsde3 小时前
【C++】C++11(1):右值引用和移动语义
开发语言·c++·算法