【设计模式】中介者模式

概念

行为模式


类图


代码

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;
}
相关推荐
咖啡八杯16 小时前
GoF设计模式——备忘录模式
java·后端·spring·设计模式
apocelipes18 小时前
常用编程语言和库的正则表达式性能对比
c语言·c++·python·性能优化·golang·开发工具和环境
槑有老呆19 小时前
从 Prompt Engineering 到 Harness Engineering:AI 编程的下一次跃迁
设计模式
HjhIron1 天前
从Prompt到Context:大模型应用开发的范式转移
设计模式·aigc·ai编程
郝学胜_神的一滴2 天前
CMake 034:生成器表达式:解耦构建时序、精简分支逻辑的终极利器
c++·cmake
咖啡八杯3 天前
GoF设计模式——中介者模式
java·后端·spring·设计模式
见过夏天3 天前
C++ 基础入门完全指南
c++
胡萝卜术3 天前
从“分数打架”到“排名投票”:为什么你的ChatBI必须用RRF?
算法·设计模式·面试
亦暖筑序4 天前
Java 8老系统Browser Agent实战:三层拦截把AI操作后台变成可审计流程
java·后端·设计模式
用户805533698034 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt