C++ Composite

Da Andreabont's Wiki.

Questo design pattern permette attraverso una interfaccia comune di trattare una collezione di oggetti come se fosse un oggetto. E' utile per definire e lavorare con strutture di dipendenza ad albero.

#include <iostream>
#include <vector>
#include <memory>

class ObjectInterface {
    
public:
    
    virtual void execute() = 0;

};

class ObjectComposite : public ObjectInterface {
    
private:
    
    std::vector<std::shared_ptr<ObjectInterface>> collection;
    
public:
    
    void execute() {
        for(auto i : this->collection) {
            i->execute();
        }
    }
    
    void add(std::shared_ptr<ObjectInterface> obj) {
        this->collection.push_back(obj);
    }
    
};

class ObjectA : public ObjectInterface {
    
public:
    
    void execute() {
        std::cout << "Object A" << std::endl;
    }

};

class ObjectB : public ObjectInterface {
    
public:
    
    void execute() {
        std::cout << "Object B" << std::endl;
    }

};

class ObjectC : public ObjectInterface {
    
public:
    
    void execute() {
        std::cout << "Object C" << std::endl;
    }

};

int main() {
    
    auto a = std::make_shared<ObjectA>();
    auto b = std::make_shared<ObjectB>();
    auto c = std::make_shared<ObjectC>();
    auto comp1 = std::make_shared<ObjectComposite>();
    auto comp2 = std::make_shared<ObjectComposite>();
    
    comp1->add(a);
    comp1->add(b);
    comp2->add(c);
    comp2->add(comp1);
    comp2->execute();
    
}

Che stampa:

Object C
Object A
Object B