组合模式
<设计模式其实很简单>笔记
将对象组成树形结构以表示“部分-整体”的层次结构。
组合模式使得用户对单个对象和组合对象的使用具有一致性。
②理解:
树和子树,即整体与部分。在树形结构中,部分和整体有着类似或相同的结构,所以可以将部分和
整体一致对待
//树中分支节点与叶子节点的抽象父类
public abstract class Component{
//组件名称
protected String componentName;
//构造方法
public Component(String componentName){
this.componentName = componentName;
}
//增加分支/叶子节点的方法
public abstract void Add(Component component);
//移除分支/叶子节点的方法
public abstract void Remove(Component component);
//按照深度显示树形结构的方法
public abstract void Show(int depth);
}
//分支节点的类
public class Composite extends Component{
private List<Component> childrenList = new ArrayList<Component>();
public Composite(String componentName){
super(componentName);
}
//增加子节点
@Override
public void Add(Component component){
childrenList.add(component);
}
//移除子节点
@Override
public void Remove(Component component){
childrenList.remove(component);
}
//展示结构
@Override
public void Show(int depth){
for(int i = 0 ; i < depth ; i++){
System.out.print("+");
}
System.out.print(componentName + "\n");
for(int i = 0 ; i < childrenList,size() ; i++){
(Component)childrenList.get(i).Show(depth+2);
}
}
}
//树叶节点
public class Leaf extends Component{
//构造函数
public Leaf(String componentName){
super(componentName);
}
//增加子节点
@Override
public void Add(Component component){
System.out.println("叶子节点无法增加新的子节点!");
}
//移除子节点
@Override
public void Remove(Component component){
System.out.println("叶子节点无法移除节点!");
}
//展示结构
@Override
public void Show(int depth){
for(int i = 0 ; i < depth ; i ++){
System.out.println("+");
}
System.out.println( componentName + "\n");
}
}
④适用的地方:
当开发的代码需要表示部分和整体的结构时
当希望用户忽略组合对象和单个对象之间的不同时
⑤优点:
组合模式可以优化处理递归或分级数据结构。分级数据结构如计算机的文件系统。