组合模式(C++)

**定义:**组合模式(Composite Pattern)是一种结构型设计模式,它将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

**应用:**文件和文件夹可以看作是一种树形结构,文件夹可以包含文件和子文件夹,而文件则不包含其他对象。使用组合模式可以方便地遍历文件系统。

代码:

cpp 复制代码
// 抽象组件类
class Component {
public:
    virtual ~Component() = default;
    virtual void add(std::shared_ptr<Component> component) = 0;
    virtual void display(int depth = 0) const = 0;
};

// 叶子节点:文件类
class File : public Component {
private:
    std::string name;
public:
    File(const std::string& name) : name(name) {}

    void add(std::shared_ptr<Component>) override {
        std::cerr << "File cannot have subcomponents!" << std::endl;
    }

    void display(int depth = 0) const override {
        for (int i = 0; i < depth; ++i) {
            std::cout << "--";
        }
        std::cout << name << std::endl;
    }
};

// 容器节点:文件夹类
class Directory : public Component {
private:
    std::string name;
    std::vector<std::shared_ptr<Component>> components;
public:
    Directory(const std::string& name) : name(name) {}

    void add(std::shared_ptr<Component> component) override {
        components.push_back(component);
    }

    void display(int depth = 0) const override {
        for (int i = 0; i < depth; ++i) {
            std::cout << "--";
        }
        std::cout << name << "/" << std::endl;
        for (const auto& component : components) {
            component->display(depth + 1);
        }
    }
};

int main() {
    // 创建文件和文件夹
    auto file1 = std::make_shared<File>("file1.txt");
    auto file2 = std::make_shared<File>("file2.txt");
    auto dir1 = std::make_shared<Directory>("dir1");
    auto dir2 = std::make_shared<Directory>("dir2");

    // 构建文件系统树
    dir1->add(file1);
    dir1->add(file2);
    dir2->add(dir1);

    // 显示文件系统树
    dir2->display();

    return 0;
}
相关推荐
一条破秋裤2 分钟前
C-数据类型
c语言·开发语言·chrome
君顾17 分钟前
从0到1课后辅导管理系统开发实战:需求文档、架构设计全复盘
java·开发语言
神仙别闹9 分钟前
基于C++ MFC RSA 实现加密程序
开发语言·c++·mfc
增量星球24 分钟前
一个 Python 脚本 + LLM 怎么替代向量检索?ProjQA 技能架构原理深度解析
开发语言·python·架构·embedding·skill
Yzzz-F33 分钟前
CF2023D
c++·算法·dp
探数API小喇叭41 分钟前
基站查询 API 怎么用?LAC、CELLID 参数详解与实战】
java·开发语言·api·基站定位
Mr.Lu ‍43 分钟前
C++开发,使用openCV API对图片进行压缩
开发语言·c++·opencv
大鹏的NLP博客44 分钟前
ONNX Runtime CUDA 推理优化实战:破解 C++ 比 Python 慢 28 倍的假象
c++·onnx·推理优化
z落落1 小时前
C# WinForm NModbus 串口通信+WinForm Modbus4 串口通信
开发语言·单片机·c#
Mojitocean1 小时前
Win开发环境配置(持续更新)
开发语言·python