1、定义
使用组合模式可以将对象组合成树状结构,并且能像使用独立对象一样使用它们。
2、前言
问题:
例如你有两类对象:产品和盒子。
- 一个盒子中可以包含多个产品或者几个较小的盒子。
- 这些小盒子中同样可以包含一些产品或者更小的盒子。
假设你希望在这些类的基础上开发一个订购系统。从下图可以看出,订单中可能包括各种产品,这些产品放置在盒子中,然后又被放入一层又一层更大的盒子总。整个结构看上去像是一棵倒过来的树。
解决方案:
组合模式建议使用一个通用结构来与「产品」和「盒子」进行交互,并且在该接口中声明一个计算总价的方法:
- 对于一个具体产品,该方法直接返回其价格
- 对于一个盒子,该方法遍历盒子中的所有项目,返回该盒子的总价格
优点:
- 1、无需了解构成树状结构的对象的具体类。
- 2、无需了解对象是简单的产品还是复杂的盒子。
你只需要调用通用接口以相同的方式对其进行处理即可。当你调用该方法后,对象会将请求沿着树结构传递下去。
3、结构
- 组件(Component)接口描述了树中简单项目和复杂项目所共有的操作。
- 叶节点(Leaf)是树的基本结构,它不包含子项目。一般情况下,叶节点最终会完成大部分的实际工作,因为它们无法将工作指派给其他部分。
- 容器(Container)——又名“组合(Composite)”——是包含叶节点或其他容器等子项目的单位。容器不知道其子项目所属的具体类,它只通过通用的组件接口与其子项目交互。容器接收到请求后会将工作分配给自己的子项目,处理中间结果,然后将最终结果返回给客户端。
- 客户端(Client)通过组件接口与所有项目交互。因此, 客户端能以相同方式与树状结构中的简单或复杂项目交互。
4、代码
Component.h:
#ifndef COMPONENT_H_
#define COMPONENT_H_
// 组件(Component)接口描述了树中简单项目和复杂项目所共有的操作,在c++中实现成抽象基类
class Graphic
{
public:
virtual void move2somewhere(int x, int y) = 0;
virtual void draw() = 0;
};
#endif //COMPONENT_H_
Leaf.h:
#ifndef LEAF_H_
#define LEAF_H_
#include<cstdio>
#include"Component.h"
//叶节点(Leaf)是树的基本结构,它不包含子项目。一般情况下,叶节点最终会完成大部分的实际工作,因为它们无法将工作指派给其他部分。
class Dot:public Graphic
{
public:
Dot(int x,int y):x_(x),y_(y){}
void move2somewhere(int x, int y) override
{
x_ += x;
y_ += y;
}
void draw() override
{
printf("在(%d,%d)处绘制点\n", x_, y_);
}
private:
int x_;
int y_;
};
class Circle:public Graphic
{
public:
explicit Circle(int r, int x,int y):radius_(r),x_(x),y_(y){}
void move2somewhere(int x, int y) override
{
x_ += x;
y_ += y;
}
void draw()override
{
printf("以(%d,%d)为圆心绘制半径为%d的圆\n", x_, y_, radius_);
}
private:
//半径与圆心坐标
int radius_;
int x_;
int y_;
};
#endif //LEAF_H_
Composite.h:
#ifndef COMPOSITE_H_
#define COMPOSITE_H_
#include"Component.h"
#include<map>
//容器(Container)——又名“组合(Composite)”——是包含叶节点或其他容器等子项目的单位
class CompoundGraphic:public Graphic
{
public:
void add(int id,Graphic* child)
{
childred_[id] = child;
}
void remove(int id)
{
childred_.erase(id);
}
void move2somewhere(int x, int y) override
{
for (auto iter = childred_.cbegin(); iter != childred_.cend(); iter++)
{
iter->second->move2somewhere(x, y);
}
}
void draw()override
{
for(auto iter = childred_.cbegin();iter != childred_.cend();iter++)
{
iter->second->draw();
}
}
private:
std::map<int,Graphic*> childred_;
};
#endif//COMPOSITE_H_
main.cpp:
#include "Composite.h"
#include "Leaf.h"
int main()
{
//组合图
CompoundGraphic* all = new CompoundGraphic();
//添加子图
Dot* dot1 = new Dot(1,2);
Circle* circle = new Circle(5,2,2);
CompoundGraphic* child_graph = new CompoundGraphic();
Dot* dot2 = new Dot(4,7);
Dot* dot3 = new Dot(3,2);
child_graph->add(0,dot2);
child_graph->add(1,dot3);
//将所有图添加到组合图中
all->add(0,dot1);
all->add(1,circle);
all->add(2,child_graph);
//绘制
all->draw();
delete all;
delete dot1;
delete dot2;
delete dot3;
delete circle;
return 0;
}