Java 设计模式 之 组合模式
http://www.verejava.com/?id=16999080076266
package com.composite.theory;
import java.util.List;
public class TestNode
{
public static void main(String[] args)
{
Node root=new DefaultNode("世界");
Node china=new DefaultNode("中国");
Node america=new DefaultNode("美国");
Node beijing=new DefaultNode("北京");
Node shanghai=new DefaultNode("上海");
china.add(beijing);
china.add(shanghai);
Node sanfancisco=new DefaultNode("三藩市");
Node niuyue=new DefaultNode("纽约");
america.add(sanfancisco);
america.add(niuyue);
root.add(china);
root.add(america);
System.out.println(root.getName());
List<Node> childeNodes=root.getChildNodes();
for(Node node :childeNodes)
{
System.out.println("----"+node.getName());
List<Node> childNodes2=node.getChildNodes();
for(Node node2 :childNodes2)
{
System.out.println("--------"+node2.getName());
}
}
}
}
package com.composite.theory;
import java.util.ArrayList;
import java.util.List;
public abstract class Node
{
protected String name;
protected List<Node> childNodes;
public Node(String name)
{
super();
this.name = name;
this.childNodes=new ArrayList<Node>();
}
public abstract void add(Node node);
public abstract void remove(int index);
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public List<Node> getChildNodes()
{
return childNodes;
}
}
package com.composite.theory;
public class DefaultNode extends Node
{
public DefaultNode(String name)
{
super(name);
}
@Override
public void add(Node node)
{
childNodes.add(node);
}
@Override
public void remove(int index)
{
childNodes.remove(index);
}
}