LinkedList<Component> children = this.getChildren(); System.out.println(temp+this.name); for (Component c : children) { c.operation(depth+1); } } }
4 测试代码
public class MainTest { public static void main(String[] args) { Composite root = new Composite("树根");
Composite branch01 = new Composite("树枝01"); Composite branch02 = new Composite("树枝02"); Composite branch03 = new Composite("树枝03"); Composite branch04 = new Composite("树枝04");
public class TreeNode { private Entry entry; private List<TreeNode> son; //getter and setter略 }
定义单例树节点
public class Tree { private TreeNode tree;
private Tree() { tree = new TreeNode(); tree.setEntry(null); tree.setSon(new ArrayList<TreeNode>()); }
public static class SingletonTreeInner { public static final Tree INSTANCE = new Tree(); }
public static Tree getInstance() { return SingletonTreeInner.INSTANCE; }
public TreeNode getTree() { return tree; } }
测试代码(根-集群-主机-虚拟机的层次关系):
public static void insertData() { Tree root = Tree.getInstance(); List<TreeNode> rootList = root.getTree().getSon();
//add cluster into root node TreeNode cluster = new TreeNode(); Entry entry1 = new Entry("cluster1"); cluster.setEntry(entry1); cluster.setSon(null); rootList.add(cluster);
//add host into cluster node TreeNode host = new TreeNode(); Entry entry2 = new Entry("host1"); host.setEntry(entry2); host.setSon(null); if(cluster.getSon() == null) { cluster.setSon(new ArrayList<TreeNode>()); } List clusterList = cluster.getSon(); clusterList.add(host);
//add vm into host node TreeNode vm = new TreeNode(); Entry entry3 = new Entry("vm1"); vm.setEntry(entry3); vm.setSon(null); if(host.getSon() == null) { host.setSon(new ArrayList<TreeNode>()); } List hostList = host.getSon(); hostList.add(vm); }