【设计模式】中介者模式

概念

行为模式


类图


代码

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;
}
相关推荐
_Twink1e9 小时前
openJiuwen 实训营 Day 1 · WorkSwarm 入门教程
开发语言·c++·openjiuwen
dong_junshuai10 小时前
每天一个开源项目#87 fmt:24.5K Stars 的 C++ 格式化核心
c++·开源·github
雪的季节10 小时前
Multisim14.0的详细中文安装步骤【附安装包】
c++
Persistent的粽子!11 小时前
C++:类与对象(二)
开发语言·c++
蒸蒸yyyyzwd12 小时前
cpp 选手备战秋招学习笔记 day23
c++·求职招聘
.YM.Z12 小时前
C++ STL 容器深度剖析:vector 与 list 的模拟实现及对比
开发语言·c++·vector·list
mengzhi啊14 小时前
QEventLoop loop配合loop.exec();替代while(1)。电脑cpu占用为0,使用while(1)cpu占用率100%
c++·qt
HugoStudio_SWAN14 小时前
洛谷 P1319 / P1320 压缩技术——同一枚硬币的正反面
c++·学习·程序人生·算法
小小晓.14 小时前
C++单例模式万字详解:6种实现演进+线程安全彻底解决+CRTP终极模板
c++·单例模式
j7~15 小时前
【C++11】C++11 新特性全套详解(列表初始化、右值引用、lambda 表达式、function 与 bind 包装器等)
c++·右值引用·lambda表达式·可变参数模板·移动语义·包装器·c++11发展史