组合模式--类似树结构
GOF对组合模式的定义是:“将对象组合成树形结构以表示“部分-整体”的层次结构。”
组合模式使得用户对单个对象和组合对象的使用具有一致性。
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.println('+');
}
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.print(componentName+'\n');
}
}
网友评论