-
Notifications
You must be signed in to change notification settings - Fork 1
/
composite.java
107 lines (86 loc) · 2.37 KB
/
composite.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
import java.util.ArrayList;
import java.util.List;
interface Component {
void operation();
void add(Component component);
void remove(Component component);
void getChild(int depth);
}
abstract class AbstractComposite implements Component {
private String name;
public AbstractComposite(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Leaf extends AbstractComposite {
public Leaf(String name) {
super(name);
}
@Override
public void operation() {
System.out.println("Leaf do something");
}
@Override
public void add(Component component) {
System.out.println("Leaf cannot add child");
}
@Override
public void remove(Component component) {
System.out.println("Leaf cannot remove child");
}
@Override
public void getChild(int depth) {
String level = "-".repeat(depth);
System.out.printf("%s%s\n", level, getName());
}
}
class Composite extends AbstractComposite {
private List<Component> list = new ArrayList<>();
public Composite(String name) {
super(name);
}
@Override
public void operation() {
System.out.println("Composite do something");
}
@Override
public void add(Component component) {
this.list.add(component);
}
@Override
public void remove(Component component) {
this.list.remove(component);
}
@Override
public void getChild(int depth) {
String level = "-".repeat(depth);
System.out.printf("%s%s\n", level, getName());
for(Component component : this.list){
component.getChild(depth + 2);
}
}
}
public class Main {
public static void main(String[] args){
Component root = new Composite("root");
Component leaf1 = new Leaf("leaf1");
Component leaf2 = new Leaf("leaf2");
root.add(leaf1);
root.add(leaf2);
Component composite1 = new Composite("composite1");
Component leaf3 = new Leaf("leaf3");
Component leaf4 = new Leaf("leaf4");
Component leaf5 = new Leaf("leaf5");
composite1.add(leaf3);
composite1.add(leaf4);
composite1.add(leaf5);
root.add(composite1);
root.getChild(0);
}
}