【设计模式】责任链模式

概念

行为模式


类图


代码

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;
}
相关推荐
Zane19942 天前
一个 new 就能创建对象,为什么还要拆出单例、工厂、建造者、原型四种模式?
设计模式
怕浪猫3 天前
一行命令复刻爆款视频,我把 Hypit 从安装跑到了出片
人工智能·设计模式·程序员
Zane19943 天前
函数式编程里的函数,其实不是你天天写的那个函数——三大编程范式的边界在哪
设计模式
Zane19944 天前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
她说..4 天前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
xiaofeiyang1505 天前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式
Shadow(⊙o⊙)5 天前
OTOL设计模式 One Thread One Loop
服务器·网络·设计模式
sarasuki6 天前
如何让LLM 能在半夜偷偷打开网易云呢?
人工智能·设计模式·agent
小王师傅666 天前
【设计模式】装饰模式(四):框架源码实战——从 Java I/O 到 Spring 到 MyBatis
java·设计模式
执明wa6 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio