public class Leaf{//葉子對象的名字 private String name = ""; public Leaf(String name){this.name = name;}}public class Composite{//用來記錄包含的其它組合對象 private Collection<Composite> childComposite = new ArrayList<Composite>(); private Collection<Leaf> childLeaf = new ArrayList<Leaf>();private String name = ""; public Composite(String name){this.name = name;}public void addComposite(Composite c){this.childComposite.add(c);}public void addLeaf(Leaf leaf){this.childLeaf.add(leaf);}// 輸出組合對象自身的結(jié)構(gòu) public void printStruct(String preStr){//先把自己輸出去System.out.println(preStr+"+"+this.name);//然后添加一個空格,表示向后縮進一個空格,輸出自己包含的葉子對象preStr+=" ";for(Leaf leaf : childLeaf){leaf.printStruct(preStr);}//輸出當(dāng)前對象的子對象了for(Composite c : childComposite){//遞歸輸出每個子對象c.printStruct(preStr);}}}public static void main(String[] args){//定義所有的組合對象Composite root = new Composite("服裝");Composite c1 = new Composite("男裝");Composite c2 = new Composite("女裝");//定義所有的葉子對象Leaf leaf1 = new Leaf("襯衣");Leaf leaf2 = new Leaf("夾克");Leaf leaf3 = new Leaf("裙子");Leaf leaf4 = new Leaf("套裝");//按照樹的結(jié)構(gòu)來組合組合對象和葉子對象root.addComposite(c1);root.addComposite(c2);c1.addLeaf(leaf1);c1.addLeaf(leaf2);c2.addLeaf(leaf3);c2.addLeaf(leaf4);//調(diào)用根對象的輸出功能來輸出整棵樹root.printStruct("");}
2. 應(yīng)用組合模式
public abstract class Component{//示意方法,子組件對象可能有的功能方法 public abstract void someOperation();public void addChild(Component child){// 缺省的實現(xiàn),拋出例外,因為葉子對象沒有這個功能,或者子組件沒有實現(xiàn)這個功能throw new UnsupportedOperationException("對象不支持這個功能");}public void removeChild(Component child){// 缺省的實現(xiàn),拋出例外,因為葉子對象沒有這個功能,或者子組件沒有實現(xiàn)這個功能throw new UnsupportedOperationException("對象不支持這個功能");}public Component getChildren(int index){// 缺省的實現(xiàn),拋出例外,因為葉子對象沒有這個功能,或者子組件沒有實現(xiàn)這個功能throw new UnsupportedOperationException("對象不支持這個功能");}}public class Leaf extends Component{public void someOperation(){// do something}}public class Composite extends Component{//用來存儲組合對象中包含的子組件對象 private List<Component> childComponents = null;public void someOperation(){if (childComponents != null){for(Component c : childComponents){//遞歸的進行子組件相應(yīng)方法的調(diào)用c.someOperation();}}}public void addChild(Component child){//延遲初始化if (childComponents == null){childComponents = new ArrayList<Component>();}childComponents.add(child);}public void removeChild(Component child){if (childComponents != null){childComponents.remove(child);}}public Component getChildren(int index){if (childComponents != null){if(index>=0 && index<childComponents.size()){return childComponents.get(index);}}return null;}}public static void main(String[] args){//定義多個Composite對象Component root = new Composite();Component c1 = new Composite();Component c2 = new Composite();//定義多個葉子對象Component leaf1 = new Leaf();Component leaf2 = new Leaf();Component leaf3 = new Leaf();//組和成為樹形的對象結(jié)構(gòu)root.addChild(c1);root.addChild(c2);root.addChild(leaf1);c1.addChild(leaf2);c2.addChild(leaf3);//操作Component對象Component o = root.getChildren(1);System.out.println(o);}