标签:style blog http color io os for 2014 div
组合模式中,整体和部分可以同等看待,基类设定一个节点接口,可以派生出叶子节点和非叶子节点。叶子节点不能添加节点,非叶子节点可以添加,组成一个典型的树形结构。
组合模式在游戏引擎的渲染树中应用很广泛。
Composite.h内容
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 Composite 20 { 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 Composite 30 { 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
标签:style blog http color io os for 2014 div
原文地址:http://www.cnblogs.com/MiniHouse/p/3975932.html