复合设计模式定义

Composite design pattern definition

在设计模式:可重用面向对象软件的元素一书中,它说:

"The composite design pattern composes objects into tree structures to represent part-whole hierarchies."

在维基百科中,复合设计模式定义为:

"The composite pattern describes a group of objects that is treated the same way as a single instance of the same type of object. The intent of a composite is to "将“对象组合成树结构以表示部分-整体层次结构。”

复合设计模式图片:

如果我的 Compositecomponents 存储为有向无环图(例如,它仅存储队列数据结构中作为 DAC 源的组件,并且这些源引用了其他组件等。 .. ) 这不是树,因为它违反了某些树结构条件。我还能说我用过复合设计模式吗?

您可以将组件存储在您喜欢的任何数据结构中。关键是您的每个组件也可以被视为“整体”。

最简单的示例是包含子视图的 CompositeView 对象。 CompositeView是一个View,它的子视图对象也是View。所以你的对象有一个共同的 interface/abstract class 。使用什么数据结构来存储子视图完全无关紧要。

在提到的树状结构中,您的 list/set/dag/whatever... 组件定义了给定父节点的一组子节点。

另一个示例可能是 BrickWallHouse。一堵墙 多块砖组成;以同样的方式,房子 四堵墙组成(例如让我说房子没有屋顶)和街区 许多房子。 Composite 模式中的 Brick 表示 Leaf,而不是 Wall、House、Block 是 Composite 的特化,但是 all 可以被视为 ConstructionComponents(或 ConstructionEntities)。