组合模式
小于 1 分钟
组合模式(Combination Pattern)也叫合成模式,有时又叫做部分-整体模式(Part-Whole),主要是用来描述部分与整体的关系,其定义如下:
Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.(将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。)
组合模式的通用类图
classDiagram
Client --> Component
Leaf --|> Component
Composite --|> Component
Component <--o Composite
class Client {
}
class Component {
+Operation()
}
class Leaf {
}
class Composite {
+Add(Parameter1: Component)
+Remove(Paramster1: Component)
+GetChild(int)
}
Component 抽象构件角色
定义参加组合的共有方法和属性,可以定义一些默认的行为或属性,比如我们例子的 getInfo 就封装到了抽象类。
Leaf 叶子构件
叶子对象,
Composite 树枝构件