设计模式之组合模式(Composite Pattern)
概述
The composite pattern allows to treat a group of objects the same way as a single object. This is for example used in tree-like object structures where a parent node’s operation influences or is dependent on child nodes. The code below organises a file folder structure as a tree. The size operation on a folder is propagated to its children which could be a file or another folder. As a client the operation only needs to be called on the parent.
组合模式就是通过把对象组成树状达到对一组对象的操作看成对一个对象的操作。
组合(Composite)模式的定义:有时又叫作部分-整体模式,它是一种将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系,使用户对单个对象和组合对象具有一致的访问性。
例子
比如我们现在要对一个文件夹(Folder)下面的所有文件(File)进行访问,这个文件夹(Folder)下面可能包含文件夹(File)和文件(File),由于Folder和File本身和树的数据结构相类似,所以用组合模式实现最好了,也就是说访问一个Folder下的所有文件,只要访问Folder就好了(一组对象的操作),访问一个文件,就访问他本身就好了(一个对象操作)。
树状结构本文类图
本文类图主要代码
接口层Node(共同部分)和部分File 整体部分(Folder),同样实现了operation 测试组合模式应用场景
组合模式的分类:在透明式的组合模式中抽象构件还声明访问和管理子类的接口;在安全式的组合模式中不声明访问和管理子类的接口,管理工作由树枝构件完成。上述例子是安全式组合模式。
1.在需要表示一个对象整体与部分的层次结构的场合。
2.要求对用户隐藏组合对象与单个对象的不同,用户可以用统一的接口使用组合结构中的所有对象的场合。