关于Java 设计模式 组合模式 Composite

关于Java 设计模式 组合模式 Composite

1、Tree.java

package com.ssm.cts.pattern.composite;

public abstract class Tree {
  // 姓名
  private String name = "";
  // 职位
  private String position = "";

  public Tree(String _name, String _position) {
    this.name = _name;
    this.position = _position;
  }

  public String getInfo() {
    String info = "";
    info = "姓名:" + this.name + "\t职位:" + this.position;
    return info;
  }
}

2、Branch.java

package com.ssm.cts.pattern.composite;

import java.util.ArrayList;

public class Branch extends Tree {

  ArrayList<Tree> subList = new ArrayList<Tree>();

  public Branch(String _name, String _position) {
    super(_name, _position);
  }

  // 增加下属
  public void addSub(Tree corp) {
    this.subList.add(corp);
  }

  // 获取下属列表
  public ArrayList<Tree> getSub() {
    return this.subList;
  }
}

3、Leaf.java

package com.ssm.cts.pattern.composite;

public class Leaf extends Tree {

  public Leaf(String _name, String _position) {
    super(_name, _position);
  }
}

4、Demo.java

package com.ssm.cts.pattern.composite;

import java.util.ArrayList;

public class Demo {

  // 测试
  public static void main(String[] args) {
    // 组装组织架构
    Branch ceo = compositeCorpTree();

    // 事业部总监
    System.out.println(ceo.getInfo());

    // 所有员工信息
    System.out.println(getTreeInfo(ceo));
  }

  // 组装树结构
  public static Branch compositeCorpTree() {
    // 事业部总监
    Branch root = new Branch("蒋智昊", "总监");
    // 两个部门经理
    Branch deptA = new Branch("叶", "规划部总经理");
    Branch deptB = new Branch("张", "研发部总经理");

    // 组长
    Branch groupA = new Branch("赵组长", "规划一组组长");
    Branch groupB = new Branch("王组长", "规划二组组长");

    // 职员
    Leaf a = new Leaf("a", "规划人员");
    Leaf b = new Leaf("b", "规划人员");
    Leaf c = new Leaf("a", "规划人员");
    Leaf d = new Leaf("b", "规划人员");
    Leaf h = new Leaf("h", "研发人员");
    Leaf i = new Leaf("i", "研发人员");

    // 开始组装
    root.addSub(deptA);
    root.addSub(deptB);

    // 部门经理
    deptA.addSub(groupA);
    deptA.addSub(groupB);

    // 规划部职员
    groupA.addSub(a);
    groupA.addSub(b);
    groupB.addSub(c);
    groupB.addSub(d);

    // 研发部职员
    deptB.addSub(h);
    deptB.addSub(i);

    return root;
  }

  // 遍历整棵树
  public static String getTreeInfo(Branch root) {
    ArrayList<Tree> subList = root.getSub();
    String info = "";
    for (Tree s : subList) {
      if (s instanceof Leaf) {
        // 无下属
        info = info + s.getInfo() + "\n";
      } else {
        // 有下属
        info = info + s.getInfo() + "\n" + getTreeInfo((Branch) s);
      }
    }

    return info;
  }

}

 

发表回复

您的电子邮箱地址不会被公开。