[设计模式]结构模式-组合模式(C++描述)
second60 20180502
1. 组合模式
组合模式,将对象组合成树形结构以表示”部份”和”整体”的层次的结构。也叫“整体-部份“模式。
组合模式使得用户对单个对象和组合对象的使用具有一致性。
部分 --- 整体
1.1优点
1. 解耦了客户程序与复杂元素内部结构
2. 让客户端像修改配置文件一样简单来完成本来需要流程控制语句来完成的功能。
1.2场景
1. 递归或分级数据结构
2. 表示对象部分-整体层次结构
2组合模式结构图
涉及角色:
1. Component: 组合中对象的声明接口,声明一个接口用于访问和管理Component子部件
2. Leaf: 在组合中表示叶子结点对象,叶子结点没有子结点
3. Composite: 定义有枝节点行为,用来存储子部件,在component接口中实现与子部件有关的操作,如add/delete等。
// 组合抽象类
class Component
{
public:
Component();
virtual ~Component();
virtual void Operation()=0;
virtual void Add(Component* );
virtual void Remove( Compoent*);
virtual Component* GetChild(int key);
};
// 整体
class Composite: public Component
{
public :
Composite();
~Composite();
void Operation()
{
vector<Component*>::iterator iter = _comVector.begin();
for(; iter != _comVector.end(); iter++)
{
(*iter)->Operation();
}
}
void Add(Component* com)
{
_comVector.push_back(com);
}
void Remove(Component* com)
{
_comVector.erase(&com);
}
void Component* GetChild(int index)
{
return _comVector[index];
}
private:
vector<Component*> _comVector;
};
//叶子节点(局部)
class Leaf: public Component
{
public:
~Leaf();
void Operation(){}
}
int main()
{
// 局部
Leaf* leaf = new Leaf();
leaf->Operation();
Leaf* leaf1 = new Leaf();
leaf1>Operation();
//整体
Composite* com = new Composite();
com->Add(leaf);
com->Add(leaf1);
com->Operation();
Component* leafOne = com->GetChild(0);
leafOne->Operation();
}
3 例子
大部分树状态,用来表示部分和整体的需求,都可以用Composite模式。
比如:树型数据结构,网站结构,文档目录等。
4 组合模式和装饰模式区别
两者结构图非常相似,但两者的用途不同
a) 装饰模式,目的是为了新加职责,通过组合方式,不生成很多子类
b) 组合模式,目的是为了部份和整体分层表示,简单处理复杂元素
5 总结
组合模式解耦了客户程序与复杂元素内部结构,从而使客户程序可以像处理简单元素一样来处理复杂元素。