C++中的组合模式

目录

[组合模式(Composite Pattern)](#组合模式(Composite Pattern))

实际应用

文件系统

组织结构

图形对象

总结


组合模式(Composite Pattern)

组合模式是一种结构型设计模式,它将对象组合成树形结构以表示"部分-整体"的层次结构。组合模式使得客户端可以统一地处理单个对象和对象组合。这个模式特别适用于需要表示层次结构的场景,例如文件系统、组织结构等。

实际应用

组合模式的核心思想是将单个对象和组合对象都实现同一个接口,从而使得客户端可以一致地处理它们。

文件系统

实现一个文件系统,其中文件和目录都可以被统一处理。

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

// 抽象基类,表示文件系统中的一个节点
class FileSystemNode {
public:
    virtual ~FileSystemNode() = default;
    virtual void display(int depth = 0) const = 0;
};

// 叶子节点,表示文件
class File : public FileSystemNode {
private:
    std::string name;
public:
    File(const std::string& name) : name(name) {}

    void display(int depth = 0) const override {
        std::cout << std::string(depth, ' ') << "File: " << name << "\n";
    }
};

// 组合节点,表示目录
class Directory : public FileSystemNode {
private:
    std::string name;
    std::vector<std::shared_ptr<FileSystemNode>> children;
public:
    Directory(const std::string& name) : name(name) {}

    void add(const std::shared_ptr<FileSystemNode>& node) {
        children.push_back(node);
    }

    void display(int depth = 0) const override {
        std::cout << std::string(depth, ' ') << "Directory: " << name << "\n";
        for (const auto& child : children) {
            child->display(depth + 2);
        }
    }
};

int main() {
    auto root = std::make_shared<Directory>("root");
    auto home = std::make_shared<Directory>("home");
    auto user = std::make_shared<Directory>("user");
    auto file1 = std::make_shared<File>("file1.txt");
    auto file2 = std::make_shared<File>("file2.txt");
    auto file3 = std::make_shared<File>("file3.txt");

    root->add(home);
    home->add(user);
    user->add(file1);
    user->add(file2);
    root->add(file3);

    root->display();

    return 0;
}

组织结构

实现一个组织结构,其中员工和部门都可以被统一处理。

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

// 抽象基类,表示组织结构中的一个节点
class OrganizationComponent {
public:
    virtual ~OrganizationComponent() = default;
    virtual void display(int depth = 0) const = 0;
};

// 叶子节点,表示员工
class Employee : public OrganizationComponent {
private:
    std::string name;
public:
    Employee(const std::string& name) : name(name) {}

    void display(int depth = 0) const override {
        std::cout << std::string(depth, ' ') << "Employee: " << name << "\n";
    }
};

// 组合节点,表示部门
class Department : public OrganizationComponent {
private:
    std::string name;
    std::vector<std::shared_ptr<OrganizationComponent>> members;
public:
    Department(const std::string& name) : name(name) {}

    void add(const std::shared_ptr<OrganizationComponent>& component) {
        members.push_back(component);
    }

    void display(int depth = 0) const override {
        std::cout << std::string(depth, ' ') << "Department: " << name << "\n";
        for (const auto& member : members) {
            member->display(depth + 2);
        }
    }
};

int main() {
    auto company = std::make_shared<Department>("Company");
    auto hr = std::make_shared<Department>("HR");
    auto it = std::make_shared<Department>("IT");
    auto alice = std::make_shared<Employee>("Alice");
    auto bob = std::make_shared<Employee>("Bob");
    auto charlie = std::make_shared<Employee>("Charlie");

    company->add(hr);
    company->add(it);
    hr->add(alice);
    it->add(bob);
    it->add(charlie);

    company->display();

    return 0;
}

图形对象

实现一个图形对象层次结构,其中基本图形(如圆形、矩形)和复合图形(由多个基本图形组成)都可以被统一处理。

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

// 抽象基类,表示图形
class Graphic {
public:
    virtual ~Graphic() = default;
    virtual void draw() const = 0;
};

// 叶子节点,表示圆形
class Circle : public Graphic {
public:
    void draw() const override {
        std::cout << "Drawing Circle\n";
    }
};

// 叶子节点,表示矩形
class Rectangle : public Graphic {
public:
    void draw() const override {
        std::cout << "Drawing Rectangle\n";
    }
};

// 组合节点,表示复合图形
class CompositeGraphic : public Graphic {
private:
    std::vector<std::shared_ptr<Graphic>> children;
public:
    void add(const std::shared_ptr<Graphic>& graphic) {
        children.push_back(graphic);
    }

    void draw() const override {
        for (const auto& child : children) {
            child->draw();
        }
    }
};

int main() {
    auto circle1 = std::make_shared<Circle>();
    auto circle2 = std::make_shared<Circle>();
    auto rectangle1 = std::make_shared<Rectangle>();

    auto composite1 = std::make_shared<CompositeGraphic>();
    composite1->add(circle1);
    composite1->add(rectangle1);

    auto composite2 = std::make_shared<CompositeGraphic>();
    composite2->add(circle2);
    composite2->add(composite1);

    composite2->draw();

    return 0;
}

总结

组合模式使得单个对象和组合对象可以被统一处理。所以无论是文件系统、组织结构还是图形对象,组合模式都能很好地表示层次结构。

相关推荐
珹洺20 小时前
C++从入门到实战(二十二)stack的介绍和使用
开发语言·c++
赵得C20 小时前
2025下半年软件设计师考前几页纸
java·开发语言·分布式·设计模式·性能优化·软考·软件设计师
幸存者letp20 小时前
为什么 max(words, key=len) 中需要传 key=len
服务器·开发语言·c#
weixin_4462608520 小时前
FastF1: 轻松获取和分析F1数据的Python包
开发语言·python
Cosmoshhhyyy20 小时前
《Effective Java》解读第26条:请不要使用原生态类型
java·开发语言
郝学胜-神的一滴20 小时前
Linux下创建线程:从入门到实践
linux·服务器·开发语言·c++·程序人生·软件工程
山土成旧客20 小时前
【Python学习打卡-Day22】启航Kaggle:从路径管理到独立项目研究的全方位指南
开发语言·python·学习
我命由我1234520 小时前
Python Flask 开发 - Flask 路径参数类型(string、int、float、path、uuid)
服务器·开发语言·后端·python·flask·学习方法·python3.11
FFZero120 小时前
C++ 内存模型与Memory Order深度解析
c++