当前位置:首页 > 开发 > 编程语言 > 设计模式 > 正文

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

发表于: 2012-09-26   作者:bylijinnan   来源:转载   浏览:
摘要: 声明: 本文只为方便我个人查阅和理解,详细的分析以及源代码请移步 原作者的博客http://chjavach.iteye.com/ import java.util.ArrayList; import java.util.List; abstract class Component { public abstract void printStruct(Str
声明:
本文只为方便我个人查阅和理解,详细的分析以及源代码请移步 原作者的博客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("");
	}

}

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

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号