c++ 结构型模式-组合(Composite)
1) 意图:
将对象的组合成树型结构以表示“部分-整体”的层次结构。Composite使得用户对单个对象和整个对象的使用具有一直性
2) 结构:
其中:
- Component 为组合中的对象声明接口
- Leaf表示“部分”的叶节点
- Composite 存储所有的节点,这样实现统一操作“整体”对象
3) 适用性:
a. 想表示对象的部分-整体层次结构
b. 希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象
4) 举例:
1 #include <iostream> 2 #include <list> 3 class Component 4 { 5 public: 6 Component() {} 7 virtual ~Component() {} 8 virtual void Operation() = 0; 9 virtual void Add(Component*) {} 10 virtual void Remove(Component*) {} 11 virtual void GetChild(int) {} 12 }; 13 class Leaf1 : public Component 14 { 15 public: 16 virtual void Operation() 17 { 18 std::cout << "print by Leaf1" << std::endl; 19 } 20 }; 21 class Leaf2 : public Component 22 { 23 public: 24 virtual void Operation() 25 { 26 std::cout << "print by Leaf2" << std::endl; 27 } 28 }; 29 class Composite : public Component 30 { 31 public: 32 typedef std::list<Component*> ComList; 33 virtual void Operation() 34 { 35 for (ComList::iterator it = m_comList.begin(); 36 it != m_comList.end(); ++it) 37 { 38 (*it)->Operation(); 39 } 40 } 41 virtual void Add(Component* p) 42 { 43 m_comList.push_back(p); 44 } 45 virtual void Remove(Component*) 46 {//略 47 } 48 virtual void GetChild(int) 49 {//略 50 } 51 private: 52 ComList m_comList; 53 }; 54 55 int main() 56 { 57 Component* leaf1 = new Leaf1(); 58 Component* leaf2 = new Leaf2(); 59 60 Component* composite = new Composite(); 61 composite->Add(leaf1); 62 composite->Add(leaf2); 63 composite->Operation(); 64 65 66 67 delete composite; 68 delete leaf1; 69 delete leaf2; 70 system("pause"); 71 }