-
Notifications
You must be signed in to change notification settings - Fork 1
/
CompositeGeometricShapes.java
81 lines (67 loc) · 2.19 KB
/
CompositeGeometricShapes.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
// Composite design pattern - geometric shapes
package structural.composite;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// Notice this is not an abstract class
class GraphicObject
{
protected String name = "Group"; // hints at what this class does
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public GraphicObject()
{
}
public String color;
public List<GraphicObject> children = new ArrayList<>();
private void print(StringBuilder stringBuilder, int depth)
{
stringBuilder.append(String.join("", Collections.nCopies(depth, "*")))
.append(depth > 0 ? " " : "")
.append((color == null || color.isEmpty()) ? "" : color + " ")
.append(getName())
.append(System.lineSeparator());
// This for loop is key of the composite design pattern
// Recursively traversing the list allows us to treat a Collection like a singular object
for (GraphicObject child : children)
child.print(stringBuilder, depth+1);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
print(sb, 0);
return sb.toString();
}
}
class Circle extends GraphicObject
{
public Circle(String color) {
name = "Circle";
this.color = color;
}
}
class Square extends GraphicObject
{
public Square(String color) {
name = "Square";
this.color = color;
}
}
class CompositeShapesDemo
{
public static void main(String[] args) {
GraphicObject drawing = new GraphicObject();
drawing.setName("My Drawing");
drawing.children.add(new Square("Red"));
drawing.children.add(new Circle("Yellow"));
GraphicObject group = new GraphicObject();
group.children.add(new Circle("Blue"));
group.children.add(new Square("Blue"));
drawing.children.add(group); // adding a GraphicObject to a graphic object
System.out.println(drawing); // This is KEY. Regardless whether it is an object (circle or square) or a list of objects, it always recursively prints!
}
}