概述
是一種結構型模式,將對象以樹形結構組織起來,以表示“部分 - 整體”的層次結構,使得客戶端對單個對象和組合對象的使用具有唯一性。
UML類圖
上面的類圖包含的角色:
Component:為參加組合的對象聲明一個公共的接口,不管是組合還是葉節點。
Leaf:在組合中表示葉子結點對象,葉子結點沒有子結點。
Composite:表示參加組合的有子對象的對象,并給出樹枝構建的行為;
代碼示例
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
import java.util.ArrayList; import java.util.List; abstract class Component { protected String name; public Component(String name) { this .name = name; } public abstract void Add(Component c); public abstract void Remove(Component c); public abstract void GetChild( int depth); } class Leaf extends Component { public Leaf(String name) { super (name); } @Override public void Add(Component c) { System.out.println( "Can not add to a leaf" ); } @Override public void Remove(Component c) { System.out.println( "Can not remove from a leaf" ); } @Override public void GetChild( int depth) { String temp = " " ; for ( int i = 0 ; i < depth; i++) { temp += "-" ; System.out.println(temp + name); } } } class Composite extends Component { private List<Component> children = new ArrayList<>(); public Composite(String name) { super (name); } @Override public void Add(Component c) { children.add(c); } @Override public void Remove(Component c) { children.remove(c); } @Override public void GetChild( int depth) { for (Component c : children) { c.GetChild(depth); } } } public class Main { public static void main(String args[]) { Composite root = new Composite( "root" ); root.Add( new Leaf( "Leaf A" )); root.Add( new Leaf( "Leaf B" )); Composite compX = new Composite( "Composite X" ); compX.Add( new Leaf( "Leaf XA" )); compX.Add( new Leaf( "Leaf XB" )); root.Add(compX); Composite compXY = new Composite( "Composite XY" ); compXY.Add( new Leaf( "Leaf XYA" )); compXY.Add( new Leaf( "Leaf XYB" )); compX.Add(compXY); root.GetChild( 3 ); } } |
應用場景
1.要求表示對象的部分-整體層次結構。
2.想要客戶端忽略組合對象與單個對象的差異,客戶端將統一地使用組合結構中的所有對象。
組合模式定義由Leaf對象和Composite對象組成的類結構;
使得客戶端變得簡單;
它使得添加或刪除子部件變得很容易。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。