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

阅读更多

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


HeadFirst设计模式_读书笔记_009_ 组合模式_第1张图片
 

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();
	}

	private List 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();
		}
	}
	

}

 

  • HeadFirst设计模式_读书笔记_009_ 组合模式_第2张图片
  • 大小: 4.5 KB
  • 查看图片附件

你可能感兴趣的:(java,组合模式)