基本概念
Composite Pattern: Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
组合模式以递归方式处理对象树中的所有项目。
该方式的最大优点在于无需了解构成树状结构的对象的具体类,也无需了解对象是简单的产品还是复杂的盒子。 只需调用通用接口以相同的方式对其进行处理即可。 当调用该方法后, 对象会将请求沿着树结构传递下去。
实现代码
组件
Component:描述树中简单项目和复杂项目所共有的操作。
叶节点
Leaf:树的基本结构, 它不包含子项目。一般情况下, 叶节点最终会完成大部分的实际工作, 因为它们无法将工作指派给其他部分。
组合容器
Container:又名 Composite,是包含叶节点或其他容器等子项目的单位。 它不知道其子项目所属的具体类, 只通过组件接口与其子项目交互。
测试类
Q & A
What are the advantages of using composite design patterns?
- It is very common to implement a part-whole hierarchy using this design pattern.
- You can easily add/delete a component to/from an existing architecture.
What are the challenges associated with using composite design patterns?
- If you want to maintain the ordering of child nodes, you need to use additional efforts.
- If you are dealing with immutable objects, you cannot simply delete those.