<<设计模式之禅(第二版)>>——第二十

2016-10-20  本文已影响26人  leiiiooo
定义:
组合模式通用类图
/*
 * 创建抽象构建
 * */
public abstract class Component {
  // 个体和整体共有的方法
  public void doSomething() {

  }
}

/*
 * 创建树枝组件
 * */
public class Composite extends Component {
  // 构架容器
  private ArrayList<Component> componentArrayList = new ArrayList<>();

  public void add(Component component) {
    this.componentArrayList.add(component);
  }

  public void remove(Component component) {
    this.componentArrayList.remove(component);
  }

  public ArrayList<Component> getChildren() {
    return this.componentArrayList;
  }
}

/*
 * 创建最小的组件
 * */
public class Leaf extends Component {
  @Override
  public void doSomething() {
    // TODO Auto-generated method stub
    super.doSomething();
  }
}
public class Client {
  public static void main(String[] args) {
    // 创建根节点
    Composite root = new Composite();
    // 创建树枝节点
    Composite branch = new Composite();
    // 创建树叶
    Leaf leaf = new Leaf();// 违反依赖倒转原则
    root.add(branch);
    branch.add(leaf);
  }

  // 递归遍历节点
  public static void display(Composite root) {
    for (Component c : root.getChildren()) {
        if (c instanceof Leaf) {
            c.doSomething();
        } else {
            display((Composite) c);
        }
    }
  }
}
优点:
缺点:
组合模式的拓展:
透明模式的通用类图
public abstract class Component {
  public void doSomething() {

  }

  public abstract void add(Component component);

  public abstract void remove(Component component);

  public abstract ArrayList<Component> getChildren();
}

public class Leaf extends Component {

  @Deprecated
  public void add(Component component) {
    // TODO Auto-generated method stub
    throw new UnsupportedOperationException();
  }

  @Deprecated
  public void remove(Component component) {
    // TODO Auto-generated method stub
    throw new UnsupportedOperationException();
  }

  @Deprecated
  public ArrayList<Component> getChildren() {
    // TODO Auto-generated method stub
    throw new UnsupportedOperationException();
  }

}

public class Client {
  public static void main(String[] args) {

  }

  public static void display(Component root) {
    for (Component c : root.getChildren()) {
        if (c instanceof Leaf) {
            c.doSomething();
        } else {
            /*
             * 不再使用强制类型转换,遵循依赖倒转原则
             */
            display(c);
        }
    }
  }
}
上一篇下一篇

猜你喜欢

热点阅读