本文共 1164 字,大约阅读时间需要 3 分钟。
目录
将对象组合成树形结构 以表示部分和整体的层次结构.
组合模式使得用户对单个对象和组合对象的使用具有一致性.
组合模式可以用于处理递归或分级数据结构。有许多关于分级数据结构的例子,组合模式非常使用与这些情形。关于分级数据结构的一个普遍性的例子是操作系统中的文件系统。文件系统由目录和文件组成。每个目录都可以装载内容。目录的内容可以是文件,也可以是目录。按照这种方式,计算机的文件系统就是以递归结构来组织的。如果想要描述这样的数据结构,那么组合模式是很适用的。
#include#include #include #include 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()"< 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()组合模式允许我们以树的形式构建对象结构,树中可以包含组合对象以及独立对象.
使用组合结构, 我们可以把相同的方法应用于组合以及独立对象. 换言之,在多数情况下,我们可以忽略掉组合对象和独立对象之间的差异。例如: line.draw(); //独立对象 pic.draw(); //组合对象 Component为所有的对象定义了一个接口,包括组合对象(picture) 以及叶子节点(line, rectangle, text).