博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
设计模式(8) - Composite组合模式
阅读量:4071 次
发布时间:2019-05-25

本文共 1164 字,大约阅读时间需要 3 分钟。

目录


1.意图

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

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

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

2.UML类图

  

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()

4. 分析

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

  使用组合结构, 我们可以把相同的方法应用于组合以及独立对象. 换言之,在多数情况下,我们可以忽略掉组合对象和独立对象之间的差异。例如:
   line.draw();       //独立对象
   pic.draw();        //组合对象
  Component为所有的对象定义了一个接口,包括组合对象(picture) 以及叶子节点(line, rectangle, text).

你可能感兴趣的文章
Understand on the tf.variable_scope and tf.name_scope
查看>>
A functional example for save and load model from Tensorflow
查看>>
sparse coding稀疏表达入门
查看>>
概率论:乘法定理、全概率公式以及贝叶斯定理
查看>>
ECSHOP发送邮件显示格林尼治时间问题的解决
查看>>
tensor shape can be flexible to determined in Tensorflow
查看>>
Tensorflow中怎么使用queue读取数据的情况下,在同一个session中边训练边测试
查看>>
使用p6spy打印hibernate或者PreparedStatement的带参数值的sql语句
查看>>
流水账...12321984543
查看>>
Tied weights in Tensorflow
查看>>
spring security对用户名和密码的校验过程
查看>>
spring security对于多登陆页面多用户数据源的使用
查看>>
2017年11月
查看>>
流水账
查看>>
Mac下PDF转EPS的方法
查看>>
php中的一些好东西
查看>>
2018新年开篇
查看>>
comments on the inverse model to solve multi-objective optimization
查看>>
iphone通信录导入到e71中
查看>>
spring security自定义登陆成功后处理
查看>>