Synthetic mode, structural mode one can also be called partial-whole mode. There are often tree structures where the composition of individual objects or individual objects is composed, and a way to complete the construction of the tree structure is needed. The compositing mode provides a unified interface for all objects in a tree structure, and the canonical tree The composition mode is more like a data structure in the process of building individual objects and composite objects. The composition pattern consists of three parts: Abstract component (Component), branch member (Composite) and leaf (leaf) component.
#include <IOSTREAM>#include<STRING>#include<vector>using namespacestd;classcomponent{ Public: Component (Const string&str): Name (str) {}Virtual voidAdd (Component * p) =0; Virtual voidDisplayintdepth) =0; stringname;};classLeaf: Publiccomponent{ Public: Leaf (Const string&str): Component (str) {}voidAdd (Component *p) {cout<<"The leaf cant add a component"<<Endl; } voidDisplayintdepth) { stringstr; inti =0; for(i =0; i<depth;i++) {str+=" "; } STR+= This-name; cout<<str<<Endl; }};classComposite: Publiccomponent{ Public: Composite (Const string&str): Component (str) {}voidAdd (Component *p) {M_compsite.push_back (P); } voidDisplayintDepth) {//The hierarchy shows that the members of the vector, in turn, call their respective display for composite inti =0; stringstr; for(i =0; i<depth;i++) {str+=" "; } STR+= This-name; cout<<str<<Endl; Vector<component *>::iterator it=M_compsite.begin (); for(; It!=m_compsite.end (); it++){ (*it)->display (depth+1); } }Private: Vector<component *>m_compsite;};intMainintargcChar*argv[]) {Composite* p =NewComposite ("Head Office"); Composite* Pchild1 =NewComposite ("subsidiaries 1"); Composite* Pchild2 =NewComposite ("Subsidiaries 2"); Composite* Pchild1child =NewComposite ("Subsidiary of 1 subsidiaries"); Leaf* Pworker =NewLeaf ("Xiao Wang");//the last leaf is no longer an add member.Pchild1child->Add (Pworker); Pchild1-Add (Pchild1child); P-Add (pchild1); P-Add (pchild2); P->display (0); return 0;}
Synthetic mode Composite