Composite
英文简单描述
Intent
You want to represent part-whole hierarchies of objects.
Composite lets clients treat individual objects and compositions of objects uniformly.
How to
Component
declares the interface for objects in the composition.
implements default behavior for the interface common to all classes, as appropriate.
Leaf
represents leaf objects in the composition. A leaf has no children.
Composite
defines behavior for components having children.
implements child-related operations in the Component interface.
Known cases
File System(Dir or File)
Filter(AndSpec、OrSpec、EqualSpec)
UML
权衡:
add和remove这些管理孩子的方法是放到component接口中好呢,还是放到Composite中好呢?
(1)放到component接口中,提供默认的实现,抛出异常,如:
Leaf类不提供对其的实现,如果client调用了,则抛出异常;Composite类实现添加child的功能;这样不用判断其类型,可以统一接口
(2)将其下移到Composite,但是不能统一接口
代码: