组合(Composite)模式又叫部分·整体模式,主要用于实现树形结构。
例子如下:
public class TreeNode{
private TreeNode parent;
private String name;
private List<TreeNode> children = new Arraylist<TreeNode>();
public TreeNode(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name= name;
}
public TreeNode getParent(){
return parent;
}
public void setParent(TreeNode parent){
this.parent = parent;
}
//添加子节点
public void addChildren(TreeNode childrenNode){
children.add(childrenNode);
}
//删除子节点
public void removeChildren(TreeNode childrenNode){
children.remove(childrenNode);
}
//取得孩子节点
public Enumeration<TreeNode> getChildrenNode(){
children.elements();
}
}
测试类:
public class Tree{
TreeNode root = null;
public Tree(String name){
root = new TreeNode(name);
}
public static void main(String [] args){
Tree tree = new Tree("A");
TreeNode rootNode = new TreeNode("B");
TreeNode childrenNode = new TreeNode("C");
rootNode.addChildren(childrenNode);
tree.root.addChildren(rootNode);
System.out.println("Build the tree finished!");
}
}