结构型模式——组合模式

组合设计模式适用于以下情况:

• 你想表示对象的部分------整体层次结构;

• 你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象;

下面是一个组合模式的示例程序:

cpp 复制代码
#include <iostream>
#include <vector>
#include <string>
#include <memory>

// 1. The Component Interface ------ Defines common operations for both files and folders
class FileSystemNode {
protected:
    std::string name_;
public:
    FileSystemNode(const std::string& name) : name_(name) {}
    virtual ~FileSystemNode() = default;

    virtual void display(int depth = 0) const = 0;
};

// 2. The Leaf Node ------ Represents individual files that cannot contain anything else
class File : public FileSystemNode {
private:
    int size_; // Unique attribute for files

public:
    File(const std::string& name, int size) : FileSystemNode(name), size_(size) {}

    void display(int depth = 0) const override {
        // Print spaces based on the tree depth for indentation
        std::string indent(depth * 2, ' ');
        std::cout << indent << "- 📄 File: " << name_ << " (" << size_ << " KB)\n";
    }
};

// 3. The Composite Node ------ Represents folders that can contain both files and other folders
class Folder : public FileSystemNode {
private:
    // A collection storing child nodes polymorphically
    std::vector<std::unique_ptr<FileSystemNode>> children_;

public:
    Folder(const std::string& name) : FileSystemNode(name) {}

    // Method to add items into the folder
    void add(std::unique_ptr<FileSystemNode> node) {
        children_.push_back(std::move(node));
    }

    void display(int depth = 0) const override {
        std::string indent(depth * 2, ' ');
        std::cout << indent << "📁 Folder: " << name_ << "\n";

        // Recursively trigger display() on all children without worrying about their exact type
        for (const auto& child : children_) {
            child->display(depth + 1); 
        }
    }
};

// 4. Client Code
int main() {
    // Create the top-level root folder
    auto rootFolder = std::make_unique<Folder>("Root");

    // Create standalone files and a sub-folder
    auto file1 = std::make_unique<File>("Config.ini", 4);
    auto subFolder = std::make_unique<Folder>("Projects");
    
    auto projectFile1 = std::make_unique<File>("main.cpp", 12);
    auto projectFile2 = std::make_unique<File>("README.md", 2);

    // Assemble the tree structure
    subFolder->add(std::move(projectFile1));
    subFolder->add(std::move(projectFile2));

    rootFolder->add(std::move(file1));
    rootFolder->add(std::move(subFolder)); // Nesting a folder inside a folder

    // Uniform treatment: Call display on the root, and the entire tree renders automatically
    std::cout << "--- Printing Directory Tree ---\n";
    rootFolder->display();

    return 0;
}

程序运行结果如下:

shell 复制代码
$ g++ -o main main.cpp
$ ./main
--- Printing Directory Tree ---
📁 Folder: Root
  - 📄 File: Config.ini (4 KB)
  📁 Folder: Projects
    - 📄 File: main.cpp (12 KB)
    - 📄 File: README.md (2 KB)
相关推荐
依然鸣1 小时前
PTA团体程序设计天梯赛L1真题讲解L1-077-080
开发语言·c++·算法·深度优先·pat考试·图论
库玛西3 小时前
现代 C++ 智能指针全景指南:从 RAII 思想到工业级实践
c语言·开发语言·c++·笔记·面试
liulilittle3 小时前
无锁并发容器的设计与实现原理
开发语言·c++·set·map·并发·无锁·lock-free
艺艺生辉4 小时前
从if-else到策略模式
后端·设计模式
qeen874 小时前
【数据结构】自平衡二叉搜索树各种旋转算法原理解析及AVL树的C++实现
数据结构·c++·算法
小林ixn4 小时前
单例模式:从弹窗管理到全局状态,一个模式搞定
前端·javascript·设计模式
Augustzero4 小时前
为什么线程不能说睡就睡?看懂等待与唤醒机制
c++·后端
程序员与背包客_CoderZ4 小时前
Linux D-Bus通信协议详解:从入门到C/C++编码实战
linux·服务器·c语言·c++·嵌入式硬件·嵌入式软件·dbus
冻柠檬飞冰走茶5 小时前
PTA基础编程题目集 7-35有理数均值(C++语言实现)
开发语言·数据结构·c++·算法·均值算法
wangchen_05 小时前
C++正则表达式
开发语言·c++·正则表达式