1. 概念
有时候又叫做部分-整体模式 存在整体和部分的时候 希望客户端忽略整体和部分的区别
2. 案例
/********************************************************************** * <pre> * FILE : Demo01.java * CLASS : Demo01 * * AUTHOR : Liaokailin * * FUNCTION : TODO * * *====================================================================== * CHANGE HISTORY LOG *---------------------------------------------------------------------- * MOD. NO.| DATE | NAME | REASON | CHANGE REQ. *---------------------------------------------------------------------- * |2014-3-5|Liaokailin| Created | * DESCRIPTION: * </pre> ***********************************************************************/ package org.demo.composite; import java.util.ArrayList; import java.util.Iterator; /** * 存在整体和部分的时候 希望客户端忽略整体和部分的区别 * Function : * @author : Liaokailin * CreateDate : 2014-3-5 * version : 1.0 */ public class Demo01 { @SuppressWarnings("unchecked") public static void main(String args[]){ Node root = new Node("root") ; root.add(new Leaf("-leaf1")) ; Node c2 = new Node("-Node1") ; c2.add(new Leaf("--leaf2")) ; c2.add(new Leaf("--leaf3")) ; root.add(c2) ; c2 = new Node("-Node2"); c2.add(new Leaf("--Leaf4")); c2.add(new Leaf("--Leaf5")); root.add(c2); root.operation() ; } } interface Component{ void operation() ; } class Leaf implements Component{ private String name ; public Leaf(String name ){this.name = name ;} public String toString(){ return this.name ;} @Override public void operation() { System.out.println(this) ; } } class Node extends ArrayList implements Component{ private String name ; public Node(String name){this.name = name ;} public String toString(){return this.name ;} @Override public void operation() { System.out.println(this) ; for(Iterator it = iterator() ;it.hasNext();){ // iterator() :获取集合中的元素 ((Component)(it.next())).operation() ; } } }
允许的结果:
root -leaf1 -Node1 --leaf2 --leaf3 -Node2 --Leaf4 --Leaf5