【设计模式】责任链模式

概念

行为模式


类图


代码

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;
}
相关推荐
Query*1 天前
Java 设计模式——工厂模式:从原理到实战的系统指南
java·python·设计模式
庸了个白1 天前
一种面向 AIoT 定制化场景的服务架构设计方案
mqtt·设计模式·系统架构·aiot·物联网平台·动态配置·解耦设计
Meteors.1 天前
23种设计模式——访问者模式 (Visitor Pattern)
设计模式·访问者模式
Vallelonga1 天前
Rust 设计模式 Marker Trait + Blanket Implementation
开发语言·设计模式·rust
en-route1 天前
设计模式的底层原理——解耦
设计模式
杯莫停丶1 天前
设计模式之:工厂方法模式
设计模式·工厂方法模式
Deschen1 天前
设计模式-抽象工厂模式
java·设计模式·抽象工厂模式
粘豆煮包1 天前
系统设计 System Design -4-2-系统设计问题-设计类似 TinyURL 的 URL 缩短服务 (改进版)
设计模式·架构
top_designer1 天前
告别“静态”VI手册:InDesign与AE打造可交互的动态品牌规范
设计模式·pdf·交互·vi·工作流·after effects·indesign
非凡的世界2 天前
深入理解 PHP 框架里的设计模式
开发语言·设计模式·php