定義(GoF《設計模式》):
將對象組合成樹形結構以表示“部分整體”的層次結構。組合模式使得用戶對單個對象和使用具有一致性。
及角色:
1.Component 是組合中的對象聲明接口,在適當的情況下,實現所有類共有接口的默認行為。聲明一個接口用於訪問和管理Component
子部件。
2.Leaf 在組合中表示葉子結點對象,葉子結點沒有子結點。
3.Composite 定義有枝節點行為,用來存儲子部件,在Component接口中實現與子部件有關操作,如增加(add)和刪除
(remove)等。
1 public static void main(String[] args) { 2 3 Component component=new Composite("根節點"); 4 Component child=new Composite("一級子節點child"); 5 Component child_1=new Leaf("一級子節點child之子節點一"); 6 Component child_2=new Leaf("一級子節點child之子節點二"); 7 child.add(child_1); 8 child.add(child_2); 9 Component child2=new Composite("一級子節點child2"); 10 component.add(child); 11 component.add(child2); 12 component.foreach(); 13 } 14 15 } 16 abstract class Component { 17 18 String name; 19 20 public Component(String s){ 21 22 this.name=s; 23 } 24 public abstract void add(Component c); 25 public abstract void remove(Component c); 26 public abstract void foreach(); 27 } 28 //組合類 29 class Composite extends Component{ 30 private List<Component>child=new ArrayList<Component> 31 (); 32 33 public Composite(String s) { 34 super(s); 35 // TODO Auto-generated constructor stub 36 } 37 38 @Override 39 public void add(Component c) { 40 child.add(c); 41 42 } 43 44 @Override 45 public void foreach() { 46 // TODO Auto-generated method stub 47 System.out.println("節點名:\t"+name); 48 for (Component c : child) { 49 c.foreach(); 50 } 51 } 52 53 @Override 54 public void remove(Component c) { 55 // TODO Auto-generated method stub 56 child.remove(c); 57 } 58 59 } 60 //不在有根節點 61 class Leaf extends Component{ 62 63 public Leaf(String s) { 64 super(s); 65 66 } 67 68 @Override 69 public void add(Component c) { 70 // TODO Auto-generated method stub 71 72 } 73 @Override 74 public void foreach() { 75 System.out.println("tself name-->"+this.name); 76 } 77 78 @Override 79 public void remove(Component c) { 80 // TODO Auto-generated method stub 81 82 } 83 84 }
執行結果:
節點名: 根節點
節點名: 一級子節點child
tself name-->一級子節點child之子節點一
tself name-->一級子節點child之子節點二
節點名: 一級子節點child2
什么情況下使用組合模式
引用大話設計模式的片段:“當發現需求中是體現部分與整體層次結構時,以及你希望用戶可以忽略組合對象與單個對象的不同,統一地使用組合結構中的所有對象時,就應該考慮組合模式了。”
參考地址:
http://blog.csdn.net/jason0539/article/details/22642281
http://blog.csdn.net/guolin_blog/article/details/9153753
http://www.2cto.com/kf/201206/137680.html