将对象组合成树形结构以表示"部分-整体"的层次结构。组合使得用户对单个对象和组合对象的使用具有一致性。
#include <iostream>
#include <string>
#include <list>
using namespace std;
// 抽象类: 公司
class Company
{
public:
Company(string name) : m_name(name) {}
virtual void add(Company* company) {};
virtual void show(int depth) {};
protected:
string m_name;
};
// 具体公司
class ConcreteCompany : public Company
{
public:
ConcreteCompany(string name) : Company(name) {}
// 增加子树
void add(Company* company)
{
pCompanyList.push_back(company);
}
void show(int depth)
{
for (int i = 0; i < depth; i++)
cout << "-";
cout << m_name << endl;
list<Company *>::iterator iter = pCompanyList.begin();
for (; iter != pCompanyList.end(); iter++)
(*iter)->show(depth + 2);
}
private:
// 公司列表
list<Company*> pCompanyList;
};
// 具体部分: 财务部
class FinanceDepartment : public Company
{
public:
FinanceDepartment(string name) : Company(name) {}
void show(int depth)
{
for (int i = 0; i < depth; i++)
cout << "-";
cout << m_name << endl;
}
};
// 具体部分: 人事部
class HRDepartment : public Company
{
public:
HRDepartment(string name) : Company(name) {}
void show(int depth)
{
for (int i = 0; i < depth; i++)
cout << "-";
cout << m_name << endl;
}
};
void test_01()
{
Company* root = new ConcreteCompany("总公司");
Company* leaf1 = new FinanceDepartment("财务部");
Company* leaf2 = new HRDepartment("人力资源部");
root->add(leaf1);
root->add(leaf2);
// 分公司A
Company* mid1 = new ConcreteCompany("分公司A");
Company* leaf3 = new FinanceDepartment("财务部");
Company* leaf4 = new HRDepartment("人力资源部");
mid1->add(leaf3);
mid1->add(leaf4);
root->add(mid1);
// 分公司B
Company* mid2 = new ConcreteCompany("分公司B");
FinanceDepartment* leaf5 = new FinanceDepartment("财务部");
HRDepartment* leaf6 = new HRDepartment("人力资源部");
mid2->add(leaf5);
mid2->add(leaf6);
root->add(mid2);
root->show(0);
delete leaf1; delete leaf2;
delete leaf3; delete leaf4;
delete leaf5; delete leaf6;
delete mid1; delete mid2;
delete root;
}
int main()
{
test_01();
system("pause");
return 0;
}