Java 中組合模型之對象結構模式的詳解
一、意圖
將對象組合成樹形結構以表示”部分-整體”的層次結構。Composite使得用戶對單個對象和組合對象的使用具有一致性。
二、適用性
你想表示對象的部分-整體層次結構
你希望用戶忽略組合對象與單個對象的不同,用戶將統一使用組合結構中的所有對象。
三、結構
四、代碼
1
2
3
4
5
6
7
8
|
public abstract class Component { protected String name; //節點名 public Component(String name){ this .name = name; } public abstract void doSomething(); } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
public class Composite extends Component { /** * 存儲節點的容器 */ private List<Component> components = new ArrayList<>(); public Composite(String name) { super (name); } @Override public void doSomething() { System.out.println(name); if ( null !=components){ for (Component c: components){ c.doSomething(); } } } public void addChild(Component child){ components.add(child); } public void removeChild(Component child){ components.remove(child); } public Component getChildren( int index){ return components.get(index); } } |
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Leaf extends Component { public Leaf(String name) { super (name); } @Override public void doSomething() { System.out.println(name); } } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public class Client { public static void main(String[] args){ // 構造一個根節點 Composite root = new Composite( "Root" ); // 構造兩個枝干節點 Composite branch1 = new Composite( "Branch1" ); Composite branch2 = new Composite( "Branch2" ); // 構造兩個葉子節點 Leaf leaf1 = new Leaf( "Leaf1" ); Leaf leaf2 = new Leaf( "Leaf2" ); branch1.addChild(leaf1); branch2.addChild(leaf2); root.addChild(branch1); root.addChild(branch2); root.doSomething(); } } 輸出結果: Root Branch1 Leaf1 Branch2 Leaf2 |
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/a992036795/article/details/52756714