组合模式(Composite Fattern)
#include <iostream>
using namespace std;
#include <list>
#include <string>
class Company {
public:
Company(string name) { m_name = name; }
virtual void AddCompany(Company* c) = 0; //增加公司
virtual void RemoveCompany(Company* c) {} //删除公司
virtual void Display(int depth) {} //显示
virtual void LineOfDuty() {} //履行职责
protected:
string m_name;
};
class ConcreteCompany :public Company {
public:
ConcreteCompany(string name):Company(name){} //这里注意:也可按照适配器模式中那种构造函数方法写
void AddCompany(Company* c) { m_children.push_back(c); }
void RemoveCompany(Company* c) { m_children.remove(c); }
void Display(int depth) {
string s = "-";
for (int i = 0; i < depth; i++) {
cout << s;
}
cout << m_name << endl;
list<Company*>::iterator it = m_children.begin();
for (; it != m_children.end(); ++it) {
(*it)->Display(depth + 2);
}
}
void LineOfDuty() {
list<Company*>::iterator it = m_children.begin();
for (; it != m_children.end(); ++it) {
(*it)->LineOfDuty();
}
}
private:
list<Company*> m_children;
};
//人力资源部
class HRDepartment :public Company {
public:
HRDepartment(string name) :Company(name) {}
void AddCompany(Company* c) {}
void RemoveCompany(Company* c) {}
void Display(int depth) {
string s = "-";
for (int i = 0; i < depth; i++) {
cout << s;
}
cout << m_name << endl;
}
void LineOfDuty() {
cout << m_name << "——员工招聘培训管理" << endl;
}
};
//财务部
class FinanceDepartment :public Company {
public:
FinanceDepartment(string name) :Company(name) {}
void AddCompany(Company* c) {}
void RemoveCompany(Company* c) {}
void Display(int depth) {
string s = "-";
for (int i = 0; i < depth; i++) {
cout << s;
}
cout << m_name << endl;
}
void LineOfDuty() {
cout << m_name << "——公司财务收支管理" << endl;
}
};
int main() {
ConcreteCompany* root = new ConcreteCompany("北京总公司");
root->AddCompany(new HRDepartment("总公司人力资源部"));
root->AddCompany(new FinanceDepartment("总公司财务部"));
ConcreteCompany* comp = new ConcreteCompany("上海华东分公司");
comp->AddCompany(new HRDepartment("华东分公司人力资源部"));
comp->AddCompany(new FinanceDepartment("华东分公司财务部"));
root->AddCompany(comp);
ConcreteCompany* comp1 = new ConcreteCompany("南京办事处");
comp1->AddCompany(new HRDepartment("南京办事处人力资源部"));
comp1->AddCompany(new FinanceDepartment("南京办事处财务部"));
comp->AddCompany(comp1);
ConcreteCompany* comp2 = new ConcreteCompany("杭州办事处");
comp2->AddCompany(new HRDepartment("杭州办事处人力资源部"));
comp2->AddCompany(new FinanceDepartment("杭州办事处财务部"));
comp->AddCompany(comp2);
cout << "结构图:" << endl;
root->Display(1);
//root->Display(2);
cout << "********************************" << endl;
cout << "职责:" << endl;
root->LineOfDuty();
return 0;
}