1.将对象组合成树形结构以表示“部分--整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
2.Composite 模式结构图
3.实现
1 #ifndef _COMPONENT_H_ 2 #define _COMPONENT_H_ 3 4 class Component 5 { 6 public: 7 Component(); 8 virtual ~Component(); 9 public: 10 virtual void Operation() = 0; 11 virtual void Add(const Component& ); 12 virtual void Remove(const Component& ); 13 virtual Component* GetChild(int ); 14 protected: 15 private: 16 }; 17 18 #endif
1 #include "Component.h" 2 3 Component::Component() 4 { 5 6 } 7 Component::~Component() 8 { 9 10 } 11 void Component::Add(const Component& com) 12 { 13 14 } 15 Component* Component::GetChild(int index) 16 { 17 return 0; 18 } 19 void Component::Remove(const Component& com) 20 { 21 22 }
1 #ifndef _COMPOSITE_H_ 2 #define _COMPOSITE_H_ 3 4 #include "Component.h" 5 #include <vector> 6 using namespace std; 7 8 class Composite:public Component 9 { 10 public: 11 Composite(); 12 ~Composite(); 13 public: 14 void Operation(); 15 void Add(Component* com); 16 void Remove(Component* com); 17 Component* GetChild(int index); 18 protected: 19 private: 20 vector<Component*> comVec; 21 }; 22 23 #endif
1 #include "Composite.h" 2 #include "Component.h" 3 #define NULL 0 //define NULL POINTOR 4 5 Composite::Composite() 6 { //vector<Component*>::iterator itend = comVec.begin(); 7 } 8 Composite::~Composite() 9 { 10 11 } 12 void Composite::Operation() 13 { 14 vector<Component*>::iterator comIter = comVec.begin(); 15 for (;comIter != comVec.end();comIter++) 16 { 17 (*comIter)->Operation(); 18 } 19 } 20 void Composite::Add(Component* com) 21 { 22 comVec.push_back(com); 23 } 24 void Composite::Remove(Component* com) 25 { 26 comVec.erase(&com); 27 } 28 Component* Composite::GetChild(int index) 29 { 30 return comVec[index]; 31 }
1 #ifndef _LEAF_H_ 2 #define _LEAF_H_ 3 4 #include "Component.h" 5 6 class Leaf:public Component 7 { 8 public: 9 Leaf(); 10 ~Leaf(); 11 void Operation(); 12 protected: 13 private: 14 }; 15 16 #endif
1 #include "Leaf.h" 2 #include <iostream> 3 4 using namespace std; 5 6 Leaf::Leaf() 7 { 8 9 } 10 Leaf::~Leaf() 11 { 12 13 } 14 void Leaf::Operation() 15 { 16 cout<<"Leaf operation....."<<endl; 17 }
1 #include "Component.h" 2 #include "Composite.h" 3 #include "Leaf.h" 4 #include <iostream> 5 6 using namespace std; 7 8 int main(int argc,char* argv[]) 9 { 10 Leaf* l = new Leaf(); 11 l->Operation(); 12 Composite* com = new Composite(); 13 com->Add(l); 14 com->Operation(); 15 Component* ll = com->GetChild(0); 16 ll->Operation(); 17 18 return 0; 19 }