设计模式二三事——组合模式
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部门,实现了组合的效果。
组合模式允许派生类包含基类实例,以此来构成相互嵌套的组合方式,可构成类似树形结构或者线性表,具体代码如下:
//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部门,实现了组合的效果。
相关文章推荐
- PropertyChangeListener简单理解
- 什么是设计模式
- 设计模式之创建型模式 - 特别的变量问题
- 七、设计模式——装饰模式
- 设计模式总结
- 设计模式之创建型模式
- 浅谈设计模式的学习
- 注册表的组织结构
- Ruby设计模式编程之适配器模式实战攻略
- 实例讲解Ruby使用设计模式中的装饰器模式的方法
- 设计模式中的模板方法模式在Ruby中的应用实例两则
- Ruby设计模式编程中对外观模式的应用实例分析
- 实例解析Ruby设计模式编程中Strategy策略模式的使用
- Ruby中使用设计模式中的简单工厂模式和工厂方法模式
- Ruby使用设计模式中的代理模式与装饰模式的代码实例
- 详解组合模式的结构及其在Ruby设计模式编程中的运用
- SQLSERVER的非聚集索引结构深度理解
- 调整SQLServer2000运行中数据库结构
- C#编程中使用设计模式中的原型模式的实例讲解
- 使用设计模式中的工厂方法模式进行C#编程的示例讲解