组合模式又称为部分整体模式,主要是为了处理树状的数据结构,提供一个统一的接口来屏蔽掉集合和个体之间的差异,以此忽略掉对象和对象集合之间的差异。例如:多级目录的显示就可以使用这种组合模式的数据结构。
public abstruct class Component() {
public abstruct addChild();
public abstruct doSomething();
}
public class Composite extends Component {
private List<Component> components = new ArrayList<>();
public addChild(Component child) {
// 添加节点
}
public doSomething() {
// 具体逻辑
}
}
public class Leaf extends Component {
private List<Component> components = new ArrayList<>();
public addChild(Component child) {
// 叶子节点不支持的api要throw error
}
public doSomething() {
// 具体逻辑
}
}
以上是组合模式的经典实现,我们发现:Component实际上声明了Leaf中并不需要的与Composite相关的api,这种不管是叶子节点函数枝干节点都有相同的api的组合模式即为透明的组合模式,这种模式能让我们统一的看待叶子节点和枝干节点,而这是破坏了类的单一职责原则换来的。