StructuralC++verifiedVerified

Composite Pattern in C++

Composes objects into tree structures to represent part-whole hierarchies, letting clients treat individual objects and compositions uniformly.

How to Implement the Composite Pattern in C++

1Step 1: Define the Component interface

class FileSystemEntry {
public:
    virtual ~FileSystemEntry() = default;
    virtual std::string name() const = 0;
    virtual int size() const = 0;
    virtual void print(int indent = 0) const = 0;
};

2Step 2: Leaf

class File : public FileSystemEntry {
    std::string name_;
    int size_;
public:
    File(std::string name, int size) : name_(std::move(name)), size_(size) {}
    std::string name() const override { return name_; }
    int size() const override { return size_; }
    void print(int indent = 0) const override {
        std::cout << std::string(indent, ' ') << name_ << " (" << size_ << "B)\n";
    }
};

3Step 3: Composite

class Directory : public FileSystemEntry {
    std::string name_;
    std::vector<std::unique_ptr<FileSystemEntry>> children_;
public:
    explicit Directory(std::string name) : name_(std::move(name)) {}

    void add(std::unique_ptr<FileSystemEntry> entry) {
        children_.push_back(std::move(entry));
    }

    std::string name() const override { return name_; }

    int size() const override {
        int total = 0;
        for (const auto& child : children_) total += child->size();
        return total;
    }

    void print(int indent = 0) const override {
        std::cout << std::string(indent, ' ') << name_ << "/\n";
        for (const auto& child : children_) child->print(indent + 2);
    }
};

int main() {
    auto root = std::make_unique<Directory>("root");
    root->add(std::make_unique<File>("readme.txt", 100));

    auto src = std::make_unique<Directory>("src");
    src->add(std::make_unique<File>("main.cpp", 500));
    src->add(std::make_unique<File>("util.cpp", 300));
    root->add(std::move(src));

    root->print();
    std::cout << "Total size: " << root->size() << "B\n";
}

Composite Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Composite Pattern in the Real World

A company’s org chart is a composite structure. An individual employee (leaf) has a salary and a name. A department (composite) also has a name and a budget—calculated by summing the salaries of all its members, which may themselves be other departments. HR can call ‘get budget’ on the CEO’s node and the entire tree is summed recursively.