組合模式的英文原文是:Compose objects into tree structures to represent part-whole hiearachies. Composite lets clients treat individual objects and compositions of objects uniformly. 意思是:將對象組合成樹形結構以表示“部分—整體”的階層,使得使用者對單個對象和組合對象的使用具有一致性。
組合模式有三個角色:
抽象構件(component)角色:定義了參加組合對象的共有的方法和屬性。
葉子構件(Leaf)角色:該角色是葉子物件,其下沒有分支,也就是沒有子節點。
數字構件(composite)角色:該角色代表了參加組合的,其下有分支的樹枝對象,它的作用是將樹枝和葉子組合成一個樹形結構,並定義出管理子物件的方法。
組合模式類圖:
各個類對應的實現代碼:
抽象構件的代碼:
package com.zz.composite;/** * 抽象構件介面 * Copyright 2015年4月25日 * created by txxs * all right reserved */public interface Component {public void operation();}
樹枝結構代碼:
package com.zz.composite;import java.util.ArrayList;/** * 定義樹枝構件 * Copyright 2015年4月25日 * created by txxs * all right reserved */public class Composite implements Component {//構件容器private ArrayList<Component> componentList = new ArrayList<Component>();//添加構件public void add(Component component){this.componentList.add(component);}//刪除構件public void remove(Component component){this.componentList.remove(component);}//擷取子構件public ArrayList<Component>getChild(){return this.getChild();}@Overridepublic void operation() {//商務邏輯代碼}}
葉子結構代碼:
package com.zz.composite;/** * 定義葉子構件 * Copyright 2015年4月25日 * created by txxs * all right reserved */public class Leaf implements Component {@Overridepublic void operation() {//業務員邏輯代碼}}
組合模式的優點:
1、調用簡單,使用者不必關心自己處理的是單個對象還是組合對象。
2、靈活增加節點,想要增加樹枝或者葉子節點只要需要找到父節點即可,不必為了增加對象組件而修改代碼
組合模式適合的情境:
1、描述對象的部分和整體的等級結構。
2、當需要忽略個體組件和組合構件的區別時
源碼下載