读《研磨设计模式》-代码笔记-组合模式

声明:
本文只为方便我个人查阅和理解,详细的分析以及源代码请移步 原作者的博客http://chjavach.iteye.com/




import java.util.ArrayList;
import java.util.List;

abstract class Component {
	
	public abstract void printStruct(String preStr);
	
	public void addChild(Component child) {
		throw new UnsupportedOperationException("addChild():not allowed.");
	}
	
	public void removeChild(Component child) {
		throw new UnsupportedOperationException("removeChild():not allowed.");
	}
	
	public Component getChild(int index) {
		throw new UnsupportedOperationException("getChild():not allowed.");
	}
}

class Leaf extends Component {
	private String name;
	public Leaf(String name) {
		this.name = name;
	}
	@Override
	public void printStruct(String preStr) {
		System.out.println(preStr + "-" + name);
	}
}

class Composite extends Component {

	private String name;

	private List<Component> list;
	
	public Composite(String name) {
		this.name = name;
	}

	public void addChild(Component child) {
		if (list == null) {
			list = new ArrayList<Component>();
		}
		list.add(child);
	}
	
	public void removeChild(Component child) {
		if (list != null) {
			list.remove(child);
		}
	}
	
	@Override
	public void printStruct(String preStr) {
		System.out.println(preStr + "+" + name);
		if (list != null) {
			preStr += " ";
			for (Component child : list) {
				child.printStruct(preStr);
			}
		}
	}
	
	
}

public class CompositePattern {

	public static void main(String[] args) {
		Component root = new Composite("服装");
		Component c1 = new Composite("男装");
		Component c2 = new Composite("女装");

		// 定义所有的叶子对象
		Component leaf1 = new Leaf("衬衣");
		Component leaf2 = new Leaf("夹克");
		Component leaf3 = new Leaf("裙子");
		Component leaf4 = new Leaf("套装");

		// 按照树的结构来组合组合对象和叶子对象
		root.addChild(c1);
		root.addChild(c2);
		c1.addChild(leaf1);
		c1.addChild(leaf2);
		c2.addChild(leaf3);
		c2.addChild(leaf4);
		// 调用根对象的输出功能来输出整棵树
		root.printStruct("");
	}

}

你可能感兴趣的:(java,设计模式)