That structural design pattern allows to create trees of objects and to interact with them as they are just a single object.
#include <iostream> #include <vector> // Component class IBird { public: virtual void fly() = 0; virtual ~IBird() {} }; // Leave class Bird : public IBird { public: void fly() { std::cout << "flap flap" << std::endl; } }; // Composite class BirdFlock : public IBird { public: void fly() { for(auto bird : m_Flock){ if(bird){bird->fly();} } } void add(IBird *bird) { m_Flock.push_back(bird); } private: std::vector<IBird*> m_Flock; }; int main() { Bird bird1, bird2, bird3, bird4, bird5; BirdFlock birdFlockPart; birdFlockPart.add(&bird1); birdFlockPart.add(&bird2); birdFlockPart.add(&bird3); BirdFlock birdFlockAll; birdFlockAll.add(&birdFlockPart); birdFlockAll.add(&bird4); birdFlockAll.add(&bird5); birdFlockAll.fly(); }
birdFlockAll | |---> birdFlockPart | | | |---> bird1 | |---> bird2 | |---> bird3 | |---> bird4 |---> bird5