组合模式(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;
}
相关推荐
C嘎嘎嵌入式开发3 小时前
(2)100天python从入门到拿捏
开发语言·python
Stanford_11063 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
Vallelonga4 小时前
Rust 中的数组和数组切片引用
开发语言·rust
Kiri霧4 小时前
Rust模式匹配详解
开发语言·windows·rust
white-persist5 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
千里马-horse5 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
Lucis__6 小时前
再探类&对象——C++入门进阶
开发语言·c++
007php0076 小时前
某大厂跳动面试:计算机网络相关问题解析与总结
java·开发语言·学习·计算机网络·mysql·面试·职场和发展
lsx2024066 小时前
HTML 字符集
开发语言
很㗊6 小时前
C与C++---类型转换
c语言·开发语言