组合模式Composite统一叶子对象和组合对象

将对象组合成树型结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
public abstract class Component {
  public abstract void someOperation();
  public void addChild(Component child) {
    throw new UnsupportedOperationException("不支持");
  }
  public void removeChild(Component child) {
    throw new UnsupportedOperationException("不支持");
  }
  public Component getChildren(int index) {
    throw new UnsupportedOperationException("不支持");
  }
}

public class Composite extends Component {
  private List<Component> childComponents = null;
  public void someOperation() {
    if(childComponents != null) {
      for(Component component : childComponents) {
        component.someOperation();
      }
    }
  }
  public void addChild(Component child) {
    if(childComponents == null) {
      childComponents = new ArrayList<Component>();
    }
    childComponents.add(child);
  }
   public void removeChild(Component child) {
    if(childComponents == null) {
      childComponents = new ArrayList<Component>();
    }
    childComponents.remove(child);
  }
  public Component getChildren(int index) {
    if(childComponents == null) {
      if(index >= 0 && index < childComponents.size()) {
        return childComponents.get(index);
      }
    }
    return null;
  }
}

public class Leaf extends Component {
  public void someOperation() {
    //
  }
}

客户端代码:
Component root = new Composite();
Component c1 = new Composite();
Component c2 = new Composite();

Component leaf1 = new Leaf();
Component leaf2 = new Leaf();
Component leaf3 = new Leaf();

root.addChild(c1);
root.addChild(c2);
root.addChild(leaf1);
c1.addChild(leaf2);
c2.addChild(leaf3);

Component o = root.getChildren(1);
System.out.println(o);

你可能感兴趣的:(设计模式)