您的位置:首页 > 其它

HeadFirst设计模式_读书笔记_009_ 组合模式

2017-04-11 10:24 176 查看
组合模式:允许将对象组合成树形结构来表现“整体/部分”的结构,让用户可以用一致的方式处理个别对象以及组合对象。



 public abstract class Node {

protected String name;
protected String desc;
public Node(String desc, String name)
{
this.name = name;
this.desc = desc;
}

public void addChild(Node node)
{
throw new UnsupportedOperationException();
}

public void removeChild(Node node)
{
throw new UnsupportedOperationException();
}

public Node getChild(int index)
{
throw new UnsupportedOperationException();
}
public Iterator createIterator()
{
throw new UnsupportedOperationException();
}

public void print()
{

}
} public class Leaf extends Node {

public Leaf(String desc, String name) {
super(desc, name);
}

public void print()
{
System.out.print("-name:" + name + "-desc:" + desc);
System.out.println();
}

} public class NodeItem extends Node {

public NodeItem(String desc, String name) {
super(desc, name);
this.childs = new ArrayList<Node>();
}

private List<Node> childs;

public void addChild(Node node)
{
this.childs.add(node);
}

public void removeChild(Node node)
{
this.childs.remove(node);
}

public Node getChild(int index)
{
return childs.get(index);
}
public Iterator createIterator()
{
return this.childs.iterator();
}

public void print()
{
System.out.println("-name:" + name + "-desc:" + desc);
for(Node child: childs)
{
child.print();
}
}





大小: 4.5 KB
查看图片附件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: