您的位置:首页 > 其它

设计模式(8) - Composite组合模式

2013-12-22 00:08 513 查看

1. 意图

将对象组合成树形结构 以表示部分和整体的层次结构.

组合模式使得用户对单个对象和组合对象的使用具有一致性.

组合模式可以用于处理递归或分级数据结构。有许多关于分级数据结构的例子,组合模式非常使用与这些情形。关于分级数据结构的一个普遍性的例子是操作系统中的文件系统。文件系统由目录和文件组成。每个目录都可以装载内容。目录的内容可以是文件,也可以是目录。按照这种方式,计算机的文件系统就是以递归结构来组织的。如果想要描述这样的数据结构,那么组合模式是很适用的。

2. UML类图



3. 代码实现

#include<iostream>
#include<vector>
#include<algorithm>
#include<functional>

using namespace std;

class Graphic
{
public:
virtual void draw() const = 0;
virtual void remove(Graphic *g) {}
virtual void add(Graphic *g) {}
virtual void getChild(int) {}
virtual ~Graphic() {}
};

class Line: public Graphic {
public:
void draw() const	{
cout<<"Line draw()"<<endl; }
};

class Rectangle:public Graphic
{
public:
void draw() const	{
cout<<"Rectangle draw()"<<endl; }
};

class Text:public Graphic
{
public:
void draw() const	{
cout<<"Text draw()"<<endl; }
};

//Composite
class Picture:public Graphic
{
public:
void draw() const 	{
//for each element in gList, call the draw member function
for_each(gList.begin(), gList.end(), mem_fun(&Graphic::draw));
}
void add(Graphic *g) {
gList.push_back(g);
}
private:
vector<Graphic*> gList;
};

int main()
{
Line line;
line.draw();

Rectangle rect;
rect.draw();

Text text;
text.draw();

Picture pic;
pic.add(&line);
pic.add(&rect);
pic.add(&text);
pic.add(&rect);
pic.draw();

return 0;
}
运行结果为:

Line draw()

Rectangle draw()

Text draw()

Line draw()

Rectangle draw()

Text draw()

Rectangle draw()

4. 分析

组合模式允许我们以树的形式构建对象结构,树中可以包含组合对象以及独立对象.

使用组合结构, 我们可以把相同的方法应用于组合以及独立对象. 换言之,在多数情况下,我们可以忽略掉组合对象和独立对象之间的差异。例如:

line.draw(); //独立对象

pic.draw(); //组合对象

Component为所有的对象定义了一个接口,包括组合对象(picture) 以及叶子节点(line, rectangle, text).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: