1 #include <iostream> 2 #include <list> 3 using namespace std; 4 //公司类,提供接口,相当于compoent 5 class Company 6 { 7 public: 8 Company(string name) 9 { 10 m_name = name; 11 } 12 13 virtual ~Company() 14 {} 15 16 virtual void Add(Company *pCom) 17 {} 18 19 virtual void Display(int depth) 20 {} 21 22 protected: 23 string m_name; 24 }; 25 26 //具体公司,相当于composite 27 class ConcreteCompany : public Company 28 { 29 public: 30 ConcreteCompany(string name): Company(name) 31 {} 32 33 virtual ~ConcreteCompany() 34 {} 35 36 //增加子树或叶子 37 void Add(Company *pCom) 38 { 39 m_listCompany.push_back(pCom); 40 } 41 42 //显示 43 void Display(int depth) 44 { 45 for(int i = 0;i < depth; i++) 46 { 47 cout<<"-"; 48 49 } 50 51 cout<< m_name << endl; 52 53 list<Company *>::iterator iter = m_listCompany.begin(); 54 55 for(; iter != m_listCompany.end(); iter++) //显示下层结点 56 { 57 (*iter)->Display(depth + 2); 58 } 59 } 60 61 private: 62 list<Company *> m_listCompany; 63 }; 64 65 //具体的部门,财务部,相当于leaf 66 class FinanceDepartment : public Company 67 { 68 public: 69 FinanceDepartment(string name):Company(name) 70 {} 71 72 virtual ~FinanceDepartment() 73 {} 74 75 //只需显示,无限添加函数,因为已是叶结点 76 virtual void Display(int depth) 77 { 78 for(int i = 0; i < depth; i++) 79 cout<<"-"; 80 81 cout<< m_name << endl; 82 } 83 }; 84 85 //具体的部门,人力资源部,相当于leaf 86 class HRDepartment :public Company 87 { 88 public: 89 HRDepartment(string name):Company(name) 90 {} 91 92 virtual ~HRDepartment() 93 {} 94 95 //只需显示,无限添加函数,因为已是叶结点 96 virtual void Display(int depth) 97 { 98 for(int i = 0; i < depth; i++) 99 { 100 cout<<"-"; 101 } 102 cout<< m_name << endl; 103 } 104 }; 105 106 ////////////////////////////////////////////////////////////////////////// 107 //测试代码 108 int main() 109 { 110 Company *root = new ConcreteCompany("总公司"); 111 Company *leaf1=new FinanceDepartment("财务部"); 112 Company *leaf2=new HRDepartment("人力资源部"); 113 root->Add(leaf1); 114 root->Add(leaf2); 115 116 //华东分公司 117 Company *mid1 = new ConcreteCompany("华东分公司"); 118 Company *leaf3=new FinanceDepartment("华东分公司财务部"); 119 Company *leaf4=new HRDepartment("华东分公司人力资源部"); 120 mid1->Add(leaf3); 121 mid1->Add(leaf4); 122 root->Add(mid1); 123 124 //南京办事处 125 Company *mid2=new ConcreteCompany("南京办事处"); 126 FinanceDepartment *leaf5=new FinanceDepartment("南京办事处财务部"); 127 HRDepartment *leaf6=new HRDepartment("南京办事处人力资源部"); 128 mid2->Add(leaf5); 129 mid2->Add(leaf6); 130 root->Add(mid2); 131 132 //杭州办事处 133 Company *mid3=new ConcreteCompany("杭州办事处"); 134 FinanceDepartment *leaf7=new FinanceDepartment("杭州办事处财务部"); 135 HRDepartment *leaf8=new HRDepartment("杭州办事处人力资源部"); 136 mid3->Add(leaf7); 137 mid3->Add(leaf8); 138 mid2->Add(mid3); 139 140 root->Display(0); 141 142 delete leaf1; 143 delete leaf2; 144 delete leaf3; 145 delete leaf4; 146 delete leaf5; 147 delete leaf6; 148 delete leaf7; 149 delete leaf8; 150 delete mid1; 151 delete mid2; 152 delete root; 153 154 return 0; 155 }