您的位置:首页 > 其它

设计模式二三事——组合模式

2016-04-28 20:21 267 查看
三、组合模式

组合模式允许派生类包含基类实例,以此来构成相互嵌套的组合方式,可构成类似树形结构或者线性表,具体代码如下:

//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部门,实现了组合的效果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息