組合模式
組合模式,將對象組合成樹形結構以表示“部分-整體”的層次結構,組合模式使得用戶對單個對象和組合對象的使用具有一致性。掌握組合模式的重點是要理解清楚 “部分/整體” 還有 ”單個對象“ 與 "組合對象" 的含義。組合模式可以讓客戶端像修改配置文件一樣簡單的完成本來需要流程控制語句來完成的功能。經典案例:系統目錄結構,網站導航結構等。(百度百科)
組合模式UML圖

組合模式代碼
package com.roc.composite; /** * 公共對象聲明 * @author liaowp * */ public abstract class Component { protected String name; public Component(String name){ this.name=name; } public Component(){ } public abstract void add(Component component); public abstract void remove(Component component); public abstract void display(int depth); public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.roc.composite; import java.util.ArrayList; import java.util.List; /** * 枝節點類 * @author liaowp * */ public class ConcreteCompany extends Component{ private List<Component> list; public ConcreteCompany(String name) { super(name); list=new ArrayList<Component>(); } public ConcreteCompany(){ list=new ArrayList<Component>(); } @Override public void add(Component component) { list.add(component); } @Override public void remove(Component component) { list.remove(component); } @Override public void display(int depth) { StringBuilder sb = new StringBuilder(""); for (int i = 0; i < depth; i++) { sb.append("-"); } System.out.println(new String(sb) + this.getName()); for (Component c : list) { c.display(depth + 2); } } }
package com.roc.composite; /** * 葉子節點 * @author liaowp * */ public class Leaf extends Component{ public Leaf(String name){ super(name); } @Override public void add(Component component) { // TODO Auto-generated method stub } @Override public void remove(Component component) { // TODO Auto-generated method stub } @Override public void display(int depth) { StringBuilder sb = new StringBuilder(""); for (int i = 0; i < depth; i++) { sb.append("-"); } System.out.println(new String(sb) + this.getName()); } }
package com.roc.composite; /** * 組合模式 * @author liaowp * */ public class Client { public static void main(String[] args) { Component root=new ConcreteCompany("root"); root.add(new Leaf("file A")); root.add(new Leaf("file B")); Component file=new ConcreteCompany("file1"); file.add(new Leaf("file C")); file.add(new Leaf("file D")); root.add(file); root.display(1); } }
組合模式適用場景
1.你想表示對象的部分-整體層次結構
2.你希望用戶忽略組合對象與單個對象的不同,用戶將統一地使用組合結構中的所有對象。
