组合模式

设计模式/结构型设计模式

简述

用来描述整体与部分的关系

可以使客户端将单纯元素与复合元素同等看待

UML图

代码

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
public abstract class Bird implements Animal {
public abstract boolean add(Bird bird);

public abstract boolean remove(Bird bird);
}

@Slf4j
public class Parrot extends Bird {
@Override
public boolean add(Bird bird) {
return false;
}

@Override
public boolean remove(Bird bird) {
return false;
}

@Override
public void run() {
log.debug("小鹦鹉 run -- >>");
}
}

// 透明模式
@Slf4j
public class AdjectiveComposite extends Bird {
private List<Bird> children = new ArrayList<>();

@Override
public boolean add(Bird bird) {
return children.add(bird);
}

@Override
public boolean remove(Bird bird) {
return children.remove(bird);
}

@Override
public void run() {
log.debug("AdjectiveComposite run -- >> ");
}
}

// 安全模式
@Slf4j
public class SecureComposite implements Animal {
private List<Animal> children = new ArrayList<>();

@Override
public void run() {
log.debug(“SecureComposite run — >>”);
}

public boolean add(Animal animal) {
return children.add(animal);
}

public boolean remove(Animal animal) {
return children.remove(animal);
}
}

// 客户端
public class Client {
public static void main(String[] args) {
// 透明模式 ,推荐
Parrot p1 = new Parrot();
p1.add(p1);
p1.remove(p1);
p1.run();
AdjectiveComposite adjectiveComposite = new AdjectiveComposite();
adjectiveComposite.add(p1);
adjectiveComposite.run();
// 安全模式
Cat cat = new Cat();
cat.run();
SecureComposite secureComposite = new SecureComposite();
secureComposite.add(cat);
secureComposite.run();
}
}