组合模式
概念:将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
适用场景:需求中体现部分与整体层次的结构时,以及希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象。
//company.h
1 #pragma once 2 #include <string> 3 #include <list> 4 #include <iostream> 5 using namespace std; 6 class Company{ 7 protected: 8 string name; 9 public: 10 Company(string name):name(name){} 11 virtual void add(Company *c)=0; 12 virtual void remove(Company *c)=0; 13 virtual void display(int depth)=0; 14 virtual void lineOfDuty()=0; 15 }; 16 17 class ConcreteCompany:public Company{ 18 private: 19 list<Company*> *listCom; 20 public: 21 ConcreteCompany(string name):Company(name){ 22 listCom = new list<Company*>; 23 }; 24 void add(Company *c){ 25 listCom->push_back(c); 26 } 27 void remove(Company *c){ 28 listCom->remove(c); 29 } 30 void display(int depth){ 31 cout << string(depth,'-') << name << endl; 32 list<Company*>::iterator it; 33 for(it=listCom->begin();it!=listCom->end();it++){ 34 (*it)->display(depth+2); 35 } 36 } 37 38 void lineOfDuty(){ 39 list<Company*>::iterator it; 40 for(it=listCom->begin();it!=listCom->end();it++){ 41 (*it)->lineOfDuty(); 42 } 43 } 44 ~ConcreteCompany(){ 45 cout << "~ConcreteCompany"<< endl; 46 delete listCom; 47 } 48 }; 49 50 class HRDepartment :public Company{ 51 public: 52 HRDepartment(string name):Company(name){ 53 54 } 55 56 void add(Company *c){} 57 void remove(Company *c){} 58 void display(int depth){ 59 cout << string(depth,'-') << name<<endl; 60 } 61 void lineOfDuty(){ 62 cout << name << "员工招聘培训管理" << endl; 63 } 64 ~HRDepartment(){ 65 cout << "~HRDepartment()" << endl; 66 } 67 }; 68 69 class FinanceDepartment :public Company{ 70 public: 71 FinanceDepartment(string name):Company(name){ 72 73 } 74 75 void add(Company *c){} 76 void remove(Company *c){} 77 void display(int depth){ 78 cout << string(depth,'-') << name<<endl; 79 } 80 void lineOfDuty(){ 81 cout << name << "公司财务收支管理" << endl; 82 } 83 ~FinanceDepartment(){ 84 cout << "~FinanceDepartment()" << endl; 85 } 86 };
//main.cpp
1 #include <iostream> 2 #include <cstring> 3 #include <stdlib.h> 4 #include "company.h" 5 6 using namespace std; 7 8 int main(){ 9 ConcreteCompany *root = new ConcreteCompany("北京总公司"); 10 HRDepartment *hd = new HRDepartment("总公司人力资源部"); 11 FinanceDepartment *fd = new FinanceDepartment("总公司财务部"); 12 13 root->add(hd); 14 root->add(fd); 15 16 ConcreteCompany *com = new ConcreteCompany("武汉分公司"); 17 HRDepartment *whd = new HRDepartment("武汉分公司人力资源部"); 18 FinanceDepartment *wfd = new FinanceDepartment("武汉分公司财务部"); 19 com->add(whd); 20 com->add(wfd); 21 22 root->add(com); 23 24 root->display(1); 25 26 root->lineOfDuty(); 27 28 delete wfd; 29 delete whd; 30 delete com; 31 delete fd; 32 delete hd; 33 delete root; 34 return 0; 35 }