【设计模式】中介者模式

概念

行为模式


类图


代码

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;
}
相关推荐
洲覆4 小时前
C++ constexpr 修饰符与函数
开发语言·数据结构·c++
我是华为OD~HR~栗栗呀5 小时前
华为od-前端面经-22届非科班
java·前端·c++·后端·python·华为od·华为
phdsky6 小时前
【设计模式】状态模式
设计模式·状态模式
bkspiderx6 小时前
C++设计模式之创建型模式:抽象工厂模式(Abstract Factory)
c++·设计模式·抽象工厂模式
Chan167 小时前
【 设计模式 | 创建型模式 建造者模式 】
java·spring boot·设计模式·java-ee·intellij-idea·建造者模式
嵌入式小李.man7 小时前
C++第十篇:const关键字
开发语言·c++
郝学胜-神的一滴7 小时前
基于Linux,看清C++的动态库和静态库
linux·服务器·开发语言·c++·程序人生
澄澈i7 小时前
设计模式学习[19]---单例模式(饿汉式/懒汉式)
学习·单例模式·设计模式
9毫米的幻想7 小时前
【Linux系统】—— 进程切换&&进程优先级&&进程调度
linux·运维·服务器·c++·学习·算法