树:根节点只有子节点,没有父节点;叶子只有父节点,没有子节点,其他节点既有父节点也有子节点;
将数的节点抽象成一个接口,利用组合模式组装成树;
树节点接口:
package com.whereta.composite; import java.util.List; /** * Vincent 创建于 2016/4/26. */ public interface ITree { int count(); String getName(); void add(ITree tree); boolean hasParent(); boolean isLeaf(); ITree getParent(); List<ITree> getChildren(); }
叶子实现:
package com.whereta.composite; import java.util.List; /** * Vincent 创建于 2016/4/26. */ public class Leaf implements ITree { private String name; private ITree parent; public Leaf(String name, ITree parent) { this.name = name; this.parent = parent; } public String getName() { return this.name; } public void add(ITree tree) { } public boolean hasParent() { return this.parent!=null; } public boolean isLeaf() { return true; } public ITree getParent() { return parent; } public List<ITree> getChildren() { return null; } public int count() { return 1; } }
非叶子节点实现:
package com.whereta.composite; import com.alibaba.fastjson.JSON; import java.util.ArrayList; import java.util.List; /** * Vincent 创建于 2016/4/26. */ public class Trunk implements ITree { private String name; private ITree parent; private List<ITree> treeList = new ArrayList<ITree>(); public Trunk(String name, ITree parent) { this.name = name; this.parent = parent; } public int count() { int num = 0; for (ITree tree : treeList) { num += tree.count(); } return num; } public void add(ITree tree) { treeList.add(tree); } public String getName() { return this.name; } @Override public String toString() { return "Trunk{" + "name='" + name + '\'' + ", parent=" + com.alibaba.fastjson.JSON.toJSONString(parent) + ", treeList=" + JSON.toJSONString(treeList) + '}'; } public boolean hasParent() { return this.parent!=null; } public boolean isLeaf() { return treeList.isEmpty(); } public ITree getParent() { return parent; } public List<ITree> getChildren() { return treeList; } }
测试:
package com.whereta.composite; /** * Vincent 创建于 2016/4/26. */ public class Main { public static void main(String[] args) { ITree trunk=new Trunk("树干",null); ITree leaf1=new Leaf("叶子1",trunk); ITree leaf2=new Leaf("叶子2",trunk); ITree leaf3=new Leaf("叶子3",trunk); trunk.add(leaf1); trunk.add(leaf2); trunk.add(leaf3); System.out.println(trunk.toString()); } }
输出:
Trunk{name='树干', parent=null, treeList=[{"leaf":true,"name":"叶子1","parent":{"children":[{"$ref":"$[0]"},{"leaf":true,"name":"叶子2","parent":{"$ref":"$[0].parent"}},{"leaf":true,"name":"叶子3","parent":{"$ref":"$[0].parent"}}],"leaf":false,"name":"树干"}},{"$ref":"$[0].parent.children[1]"},{"$ref":"$[0].parent.children[2]"}]}
个人博客:http://www.whereta.com