【设计模式】中介者模式

概念

行为模式


类图


代码

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;
}
相关推荐
eggwyw10 小时前
关于C++为什么不加入垃圾回收机制解析
开发语言·c++
曦樂~20 小时前
Cpp面筋
c语言·c++
道尔柯南20 小时前
C++ string 类详解:从常用接口到深拷贝,彻底掌握字符串处理
android·java·c++
2601_967979121 天前
设计模式 - 访问者模式
设计模式·访问者模式·应用场景·对象结构·操作分离
十二1 天前
【洛谷题解】P1083 [NOIP 2012 提高组] 借教室(二分答案 + 差分)
数据结构·c++·算法·蓝桥杯
D e re k ZH1 天前
C++ 从零入门(一):基础语法与程序结构
数据结构·c++·算法
zjxtxdy1 天前
C++面向对象程序开发-类与对象
开发语言·c++
東隅已逝,桑榆非晚1 天前
算法6. 双指针法-查找总价格为目标的两个商品
c++·学习·算法
qq_406981031 天前
c++拷贝构造函数
开发语言·c++
是2的10次方啊1 天前
设计模式与生活⑭:一栋楼,共用一份热
设计模式