结构型模式
8)组合模式
当需要以树形结构来表示部分 - 整体的层次结构时使用。
组合模式中只有一种角色,就是要表示的对象。
//对象基类
class Department{
public:
Department(string strName): m_strName(strName){}
void addSubDepartment(Department* p){
m_vecDep.push_back(p);
}
virtual ~Department(){
list<Department*>::iterator it;
for(it = m_vecDep.begin();it!=m_vecDep.end();it++){
if(*it!=NULL){
delete (*it);
(*it) = NULL;
}
}
}
private:
string m_strName;
list<Department* > m_vecDep; //这里为核心,就是包含了指向同样类型指针的容器
};
class Level1Depart : public Department{
public:
Level1Depart(string name) : Department(name){}
};
class Level2Depart : public Department{
public:
Level2Depart(string name):Department(name){}
};
int main()
{
//一级部门
Department* a0 = new Department("A1");
//二级部门
Department* b1 = new Level1Depart("B1");
Department* b2 = new Level1Depart("B2");
//三级部门
Department* c1 = new Level2Depart("C1");
Department* c2 = new Level2Depart("C2");
Department* c3 = new Level2Depart("C3");
Department* c4 = new Level2Depart("C4");
a0->addSubDepartment(b1);
a0->addSubDepartment(b2);
b1->addSubDepartment(c1);
b1->addSubDepartment(c2);
b2->addSubDepartment(c3);
b2->addSubDepartment(c4);
}