【设计模式】责任链模式

概念

行为模式


类图


代码

cpp 复制代码
#include <iostream>
#include <vector>

using namespace std;

class ComponentWithContextualHelp {
public:
    virtual void ShowHelp() = 0;
};

class Component : public ComponentWithContextualHelp {
public:
    void ShowHelp() override {
        cout << "Component show help." << endl;
        if (tooltipText.empty()) {
            tooltipText = "Firstly assign Component show help.\n";
        } else {
            tooltipText = "Component help already shown.\n";
        }

        cout << tooltipText;
    }

private:
    string tooltipText;
};

class Container : public Component {
public:
    void ShowHelp() override {
        cout << "Container show help." << endl;
        for (const auto& child : children) {
            child->ShowHelp();
        }
    }

    void Add(Component* child) {
        children.emplace_back(child);
        child = this;
    }

protected:
    vector<Component*> children;
};

class Button : public Component {};

class Panel : public Container {
public:
    void ShowHelp() override {
        cout << "Panel show help." << endl;
        if (modalHelpText.empty()) {
            modalHelpText = "Firstly assign Panel show help.\n";
        } else {
            modalHelpText = "Panel help already shown.\n";
        }
        cout << modalHelpText;

        for (const auto& child : children) {
            child->ShowHelp();
        }
    }

private:
    string modalHelpText;
};

class Dialog : public Container {
public:
    void ShowHelp() override {
        cout << "Dialog show help." << endl;
        if (wikiPageURL.empty()) {
            wikiPageURL = "Firstly assign Dialog show help.\n";
        } else {
            wikiPageURL = "Dialog help already shown.\n";
        }
        cout << wikiPageURL;

        for (const auto& child : children) {
            child->ShowHelp();
        }
    }
private:
    string wikiPageURL;
};

int main(int argc, char *argv[]) {
    auto dialog = new Dialog();
    auto panel = new Panel();
    auto ok = new Button();
    auto cancel = new Button();

    panel->Add(ok);
    panel->Add(cancel);
    dialog->Add(panel);

    dialog->ShowHelp();

    delete dialog;
    delete panel;
    delete ok;
    delete cancel;

    return 0;
}
相关推荐
灰子学技术34 分钟前
Envoy 使用的设计模式技术文档
设计模式
Carl_奕然10 小时前
【智能体】Agent的四种设计模式之:ReAct
人工智能·设计模式·语言模型
二哈赛车手12 小时前
新人笔记---多策略搭建策略执行链实现RAG检索后过滤
java·笔记·spring·设计模式·ai·策略模式
楼田莉子12 小时前
仿Muduo的高并发服务器:Channel模块与Poller模块
linux·服务器·c++·学习·设计模式
geovindu1 天前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
嵌入式学习_force1 天前
02_state
设计模式·蓝牙
qcx232 天前
Warp源码深度解析(七):Token预算策略——双轨计费、上下文溢出与摘要压缩
人工智能·设计模式·rust·wrap
Cosolar2 天前
提示词工程面试题系列 - Zero-Shot Prompting 和 Few-Shot Prompting 的核心区别是什么?
人工智能·设计模式·架构
geovindu2 天前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式
钝挫力PROGRAMER2 天前
贫血模型的改进
java·开发语言·设计模式·架构