结构型模式-----组合模式(Composite)

1、组合模式        (树型结构 : 自身一对多)

            将对象组合成树形结构以表示“部分--整体”的层次结构,Composite使得用户对单个对象和组合对象的使用具有一致性。

 

        结构型模式-----组合模式(Composite)_第1张图片

 

     实例一

 

public class TreeNode {

	private String name;
	private TreeNode parent;
	private List<TreeNode> children = new LinkedList<TreeNode>();

	public TreeNode(final String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	public void setName(final String name) {
		this.name = name;
	}

	public TreeNode getParent() {
		return this.parent;
	}

	public void setParent(final TreeNode parent) {
		this.parent = parent;
	}

	public List<TreeNode> getChildren() {
		return this.children;
	}

	public void setChildren(final List<TreeNode> children) {
		this.children = children;
	}

	public TreeNode add(final TreeNode node) {
		this.children.add(node);
		return this;
	}

	public TreeNode remove(final TreeNode node) {
		this.children.remove(node);
		return this;
	}
}

public class Tree {

	private TreeNode root;

	public Tree(final String rootName) {
		this.root = new TreeNode(rootName);
	}

	public TreeNode getRoot() {
		return this.root;
	}

	public static void main(final String[] args) {
		final Tree tree = new Tree("root");
		tree.getRoot().add(new TreeNode("a")).add(new TreeNode("b"));
	}
}

 

       

你可能感兴趣的:(23种设计模式,组合对象)