-
Notifications
You must be signed in to change notification settings - Fork 1
/
StaticDecorator.java
108 lines (87 loc) · 2.31 KB
/
StaticDecorator.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
108
// Static decorator
package structural.decorator.statik;
import java.util.function.Supplier;
interface Shape
{
String info();
}
class Circle implements Shape
{
private float radius;
public Circle() {}
public Circle(float radius) {
this.radius = radius;
}
void resize(float factor)
{
radius *= factor;
}
@Override
public String info() {
return "A circle of radius " + radius;
}
}
class Square implements Shape
{
private float side;
public Square() {}
public Square(float side) {
this.side = side;
}
@Override
public String info() {
return "A square ";
}
}
// Build static decorators to extend Shapes above
class ColoredShape<T extends Shape> implements Shape
{
private Shape shape;
private String color;
// Instead of passing type, we pass constructor to that type
public ColoredShape(Supplier<? extends T> constructor,
String color)
{
shape = constructor.get(); // we are constructing the shape from the supplier we are given
this.color = color;
}
public ColoredShape(Shape shape, String color) {
this.shape = shape;
this.color = color;
}
@Override
public String info() {
return shape.info() + " has the color " + color;
}
}
class TransparentShape<T extends Shape>
implements Shape
{
private Shape shape;
private int transparency;
public TransparentShape(Supplier<? extends T> constructor,
int transparency)
{
shape = constructor.get();
this.transparency = transparency;
}
@Override
public String info() {
return shape.info()+ " has "
+ transparency + "% transparency";
}
}
class StaticDecoratorDemo
{
public static void main(String[] args)
{
ColoredShape<Square> blueSquare =
new ColoredShape<>(() -> new Square(20),"blue");
System.out.println(blueSquare.info());
TransparentShape<ColoredShape<Circle>> myCircle =
new TransparentShape<>(() ->
new ColoredShape<>(() -> new Circle(5), "green"), 50);
System.out.println(myCircle.info());
// myCircle.resize() - not possible since TransparentShape does not inherit from circle
}
}