组合模式(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;
}
相关推荐
z落落3 分钟前
C#WinForm控件实战:Panel与单选框动态创建
开发语言·c#
ptc学习者4 分钟前
python 中描述符@property property 大概的样子
开发语言·python
zmzb01035 分钟前
Python课后习题训练记录Day129
开发语言·python
张忠琳14 分钟前
【Go 1.26.4】Golang Map 深度解析
开发语言·后端·golang
Vertira14 分钟前
如何对QT开发的软件进行打包[已解决]
开发语言·qt
AI人工智能+电脑小能手17 分钟前
【大白话说Java面试题 第110题】【并发篇】第10题:CAS 存在哪些问题?
java·开发语言·面试
石一峰69925 分钟前
C 语言函数设计模式实战经验
c语言·开发语言·设计模式
sitellla31 分钟前
Pydub:用 Python 处理音频,不写废话
开发语言·python·其他·音视频
xingyuzhisuan39 分钟前
缓存命中率提升方案:从 30% 优化至 82% 全流程优化记录
java·开发语言·缓存·ai
郑洁文1 小时前
基于Python的恶意流量监测系统的设计与实现
开发语言·python