【设计模式】责任链模式

概念

行为模式


类图


代码

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;
}
相关推荐
七月丶7 小时前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞7 小时前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼8 小时前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟1 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder1 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室1 天前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦2 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式