组合模式:将对象组合成树形结构以表示‘部分 - 整体’的层次结构。组合模式使得模式使得用户对单个对象和组合对象的使用具有一致性。
透明方式:在Component
中申明所有用来管理子对象的方法。使接口具有一致性。使用起来没区别,但是remove
和add
没有实现,使用没有意义
安全方式:在Component
中不用申明add和remove
方法,那么子类的leaf
也就不用去实现他,不过由于不透明,所以树叶和树枝不具有相同的接口,客户端调用要做相应的判断,带来不便。
#include <iostream>
#include <list>
#include <algorithm>
#include <numeric>
using namespace std;
inline void coutName(int depth,string name) {
string dash = "-";
for (int i = 0; i< depth; i++) {
cout<<"-";
}
cout<<name<<endl;
}
class Company {
protected:
string name;
public:
Company(string name):name(name) {
}
virtual void Add(Company * c){};
virtual void Remove(Company * c){};
virtual void Display(int depth){};
virtual void LineOfDuty(){};
};
typedef list<Company *> CompanyList;
class ConcreteCompany:public Company {
private:
CompanyList children ;
public:
ConcreteCompany (string name):Company(name){}
void Add(Company * c){ children.push_front(c); };
void Remove(Company * c){children.remove(c);};
void Display(int depth){
cout<< '-' * depth<<"name"<<endl;
CompanyList::iterator iter;
for (iter = children.begin(); iter != children.end(); iter++) {
(*iter)->Display(depth + 2);
}
};
void LineOfDuty(){
CompanyList::iterator iter;
for (iter = children.begin(); iter != children.end(); iter++) {
(*iter)->LineOfDuty();
}
}
};
class HRDepartment: public Company {
public:
HRDepartment(string name):Company(name) {}
void Add(Company * c){ };
void Remove(Company * c){};
void Display(int depth){
coutName(depth,name);
};
void LineOfDuty(){
cout<<name<<" 员工招聘培训管理"<<endl;
}
};
class FinanceDepartment : public Company {
public:
FinanceDepartment(string name):Company(name){}
void Add(Company * c){ };
void Remove(Company * c){};
void Display(int depth){
coutName(depth,name);
};
void LineOfDuty(){
cout<<name<<" 公司财务收支管理"<<endl;
}
};
void testLesson15(){
ConcreteCompany * root = new ConcreteCompany("北京总公司");
root->Add(new HRDepartment("总公司人力"));
root->Add(new FinanceDepartment("总公司财务"));
ConcreteCompany * comp = new ConcreteCompany("上海分公司");
comp->Add(new HRDepartment("上海分人力"));
comp->Add(new FinanceDepartment("上海分财务"));
root->Add(comp);
ConcreteCompany * comp1 = new ConcreteCompany("南京办事处");
comp1->Add(new HRDepartment("南京办人力"));
comp1->Add(new FinanceDepartment("南京办财务"));
comp->Add(comp1);
ConcreteCompany * comp2 = new ConcreteCompany("杭州办事处");
comp2->Add(new HRDepartment("杭州办人力"));
comp2->Add(new FinanceDepartment("杭州办财务"));
comp->Add(comp2);
cout<< "结构图:"<<endl;
root->Display(1);
cout<<" 指责:"<<endl;
root->LineOfDuty();
}
需求中是体现部分和整体层次的结构时,希望用户可以忽略组合对象与单个对象的不同。统一的使用组合结构中的所有对象,就该考虑组合模式。