组合模式(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;
}
相关推荐
幸运小圣4 小时前
for...of vs for 循环全面对比【前端JS】
开发语言·前端·javascript
沙威玛_LHE4 小时前
C++ 头文件:语言功能的 “模块化工具箱”(第三章)
c++
liu****4 小时前
12.线程同步和生产消费模型
linux·服务器·开发语言·c++·1024程序员节
顺顺 尼4 小时前
了解和使用多态
c++
学习编程的Kitty5 小时前
JavaEE初阶——多线程(5)单例模式和阻塞队列
java·开发语言·单例模式
0x00075 小时前
翻译《The Old New Thing》- 为什么 SHFormatDateTime 要接收一个未对齐的 FILETIME?
c++·windows
懒羊羊不懒@5 小时前
JavaSe—Stream流☆
java·开发语言·数据结构
Js_cold5 小时前
(* clock_buffer_type=“NONE“ *)
开发语言·fpga开发·verilog·vivado·buffer·clock
周杰伦_Jay5 小时前
【Go微服务框架深度对比】Kratos、Go-Zero、Go-Micro、GoFrame、Sponge五大框架
开发语言·微服务·golang
杰瑞哥哥6 小时前
标准 Python 项目结构
开发语言·python