组合模式原理:组合模式的作用是讲继承同一父类的不同子类对象组合起来,形成一个树形的结构,例如公司的部门组织
代码如下
#include <iostream> #include <string> #include <list> using namespace std; /************************************************************************/ /* 组合模式的作用是讲继承同一父类的不同子类对象组合起来 */ /************************************************************************/ class Company { public: Company(string name) { m_name = name; } virtual void show(int depth) { } virtual void Add(Company *pComp) { } protected: string m_name; }; //组合类 class ConcreteCompany:public Company { public: ConcreteCompany(string name):Company(name) { } virtual void Add(Company *pCompany) { m_ListCompany.push_back(pCompany); } virtual void show(int depth) { list<Company*>::iterator iter = m_ListCompany.begin(); for (;iter != m_ListCompany.end();++iter) { (*iter)->show(depth + 1); } } private: list<Company *> m_ListCompany ; }; //具体类 class FinanceDepartment:public Company { public: FinanceDepartment(string name):Company(name){} virtual void show(int depth) { for (int i = 0;i < depth;++i) { cout << "-"; } cout << m_name << endl; } }; class ITDepartment:public Company { public: ITDepartment(string name):Company(name){} virtual void show(int depth) { for (int i = 0;i < depth;++i) { cout << "-" ; } cout << m_name << endl; } }; int main() { Company *root = new ConcreteCompany("总公司"); Company *leaf1 = new FinanceDepartment("财务部"); Company *leaf2 = new ITDepartment("信息部"); root->Add(leaf1); root->Add(leaf2); Company *mid = new ConcreteCompany("分公司"); Company *mleaf1 = new FinanceDepartment("财务部"); Company *mleaf2 = new ITDepartment("信息部"); mid->Add(mleaf1); mid->Add(mleaf2); root->Add(mid); root->show(1); return 0; }