In the combination mode, the whole and part can be viewed in the same way. The base class sets a node interface to derive leaf nodes and non-leaf nodes. Leaf nodes cannot be added. Non-leaf nodes can be added to form a typical tree structure.
The combination mode is widely used in the rendering tree of the game engine.
Composite. H Content
1 #ifndef Composite_H_H 2 #define Composite_H_H 3 4 #include<iostream> 5 #include<vector> 6 using namespace std; 7 8 class Composite 9 {10 public:11 Composite(string str) : name(str) {}12 virtual ~Composite() {}13 virtual void add(Composite *composite) = 0;14 virtual void display() = 0;15 protected:16 string name;17 };18 19 class Leaf : public Composite20 {21 public:22 Leaf(string str) : Composite(str) {}23 virtual void add(Composite *composite) {}24 virtual void display() { cout << name << " "; }25 private:26 27 };28 29 class Component : public Composite30 {31 public:32 Component(string str) : Composite(str) { }33 virtual void add(Composite *composite) { vecChildren.push_back(composite); }34 virtual void display(){35 cout << name << " " << endl;36 for(size_t i=0; i<vecChildren.size(); ++i){37 vecChildren[i]->display();38 }39 }40 private:41 vector<Composite*> vecChildren;42 };43 44 void CompositeTest()45 {46 Composite *com1 = new Component("A");47 Composite *leaf1 = new Leaf("B");48 Composite *leaf2 = new Leaf("C");49 com1->add(leaf1);50 com1->add(leaf2);51 52 Composite *com2 = new Component("D");53 Composite *leaf4 = new Leaf("E");54 Composite *leaf5 = new Leaf("F");55 com2->add(leaf4);56 com2->add(leaf5);57 58 com1->add(com2);59 60 com1->display();61 62 }63 64 #endif
Design mode 9-Combination Mode