/
Component-组合模式.java
58 lines (46 loc) · 1.25 KB
/
Component-组合模式.java
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
// --------------------- 抽象构件
public abstract class Component {
public void doSomething() {
System.out.println("Component doSomething...");
}
}
// --------------------- 树枝构件
public class Composite extends Component {
private ArrayList<Component> list = new ArrayList<Component>();
public void add(Component component) {
list.add(component);
}
public void remove(Component component) {
list.remove(component);
}
public ArrayList<Component> getChildren() {
return list;
}
}
// --------------------- 树叶构件
public class Leaf extends Component {
public void doSomething() {
System.out.println("Leaf doSomething...");
}
}
// --------------------- test code
public static void main(String[] args) {
Composite root = new Composite();
Composite branch = new Composite();
Leaf leaf = new Leaf();
root.add(branch);
branch.add(leaf);
root.doSomething();
display(root);
}
public static void display(Composite root) {
for (Component ele : root.getChildren()) {
if (ele instanceof Leaf) {
ele.doSomething();
}
else {
ele.doSomething();
display((Composite) ele);
}
}
}