三、组合模式
组合模式允许派生类包含基类实例,以此来构成相互嵌套的组合方式,可构成类似树形结构或者线性表,具体代码如下:
//the base composite
class Company
{
public:
Company( char* name )
{
m_p = p;
}
virtual void Add( Company* pCom ){}
virtual void Show( int depth ){}
protected:
char* m_p;
};
class FinanceDepartment : public Company
{
public:
FinanceDepartment( char* name ) : Company( name )
{
}
virtual void Show( int depth )
{
for( int i = 0; i < depth; ++i )
{
cout<<"-";
}
cout<<m_p<<endl;
}
};
class HRDepartment : public Company
{
public:
HRDepartment( char* name ) : Company( name )
{
}
virtual void Show( int depth )
{
for( int i = 0; i < depth; ++i )
{
cout<<"-";
}
cout<<m_p<<endl;
}
};
class ConcreteCompany : public Company
{
public:
ConcreteCompany( char* name ) : Company( name )
{
m_p = name;
}
virtual void Add( Company* pCom )
{
m_list.push_back( pCom );
}
virtual void Show( int depth )
{
for( int i = 0; i < depth; ++i )
{
cout<<"-";
}
cout<<m_p<<endl;
for( vector< Company* >::size_type i = 0; i < m_list.size(); ++i )
{
m_list[ i ]->Show( depth + 2 );
}
}
private:
vector< Company* > m_list; //the container of the composite
};
上述代码中,公司类是一个基本抽象类,而金融部门和HR部门是派生类,具体的公司可以包含金融部门和HR部门,而HR部门里面有可以包含各自的金融部门或者金融部门可以包含各自的HR部门,实现了组合的效果。