一、組合模式簡介(Brief Introduction)
組合模式,將對象組合成樹形結構以表示“部分-整體”的層次結構,組合模式使得用戶對單個對象和組合對象的使用具有一致性。二、解決的問題(What To Solve)
解決整合與部分可以被一致對待問題。三、組合模式分析(Analysis)
Component:抽象的組件對象,爲組合中的對象聲明接口,讓客戶端可以通過這個接口來訪問和管理整個對象結構,可以在裏面爲定義的功能提供缺省的實現
Leaf:葉子節點對象,定義和實現葉子對象的行爲,不再包含其他的子節點對象
Composite:組合對象,通常會存儲子組件,定義包含子組件的那些組件的行爲,並實現在組件接口中定義的與子組件有關的操作
Client:客戶端,通過組件接口來操作組合結構裏面的組件對象
四、實例代碼
1、Component抽象類
public abstract class Component {
public abstract void someOperation(String str);
public void addChild(Component child){
throw new UnsupportedOperationException("對象不支持這個功能");
}
public void removeChild(Component child) {
throw new UnsupportedOperationException("對象不支持這個功能");
}
public Component getChildren(int index) {
throw new UnsupportedOperationException("對象不支持這個功能");
}
}
2、Composite組合對象
public class Composite extends Component {
private List<Component> components = null;
private String name = "";
public Composite(String name){
this.name = name;
}
public void someOperation(String str) {
System.out.println(str+"+"+this.name);
//如果還包含有子組件,那麼就輸出這些子組件對象
if(this.components!=null){
//然後添加一個空格,表示向後縮進一個空格
str+=" ";
//輸出當前對象的子對象了
for(Component c : components){
//遞歸輸出每個子對象
c.someOperation(str);
}
}
}
public void addChild(Component child){
if (components == null) {
components = new ArrayList<Component>();
}
components.add(child);
}
}
3、Leaf葉子節點對象
public class Leaf extends Component {
private String name = "";
public Leaf(String name){
this.name = name;
}
public void someOperation(String str) {
System.out.println(str+"-"+name);
}
}
4、客戶端調用
public class Client {
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("戴爾筆記本");
Component leaf5 = new Leaf("華碩筆記本");
root.addChild(c1);
root.addChild(c2);
c1.addChild(leaf1);
c1.addChild(leaf2);
c2.addChild(leaf3);
c2.addChild(leaf4);
c2.addChild(leaf5);
root.someOperation("|");
}
}
運行結果: