-
Notifications
You must be signed in to change notification settings - Fork 1
/
DynamicDecorator.java
105 lines (84 loc) · 2.1 KB
/
DynamicDecorator.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
// Dynamic decorator
package structural.decorator.dynamic;
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 decorators to extend Shapes above
class ColoredShape implements Shape
{
private Shape shape; // which shape we are decorating
private String 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 implements Shape
{
private Shape shape; // shape we are decorating
private int transparency;
public TransparentShape(Shape shape, int transparency) {
this.shape = shape;
this.transparency = transparency;
}
@Override
public String info() {
return shape.info()+ " has "
+ transparency + "% transparency";
}
}
class DynamicDecoratorDemo
{
public static void main(String[] args)
{
// A regular circle
Circle circle = new Circle(10);
System.out.println(circle.info());
// A colored square
ColoredShape blueSquare = new ColoredShape(
new Square(20), "blue"
);
System.out.println(blueSquare.info());
// A transparent, colored circle
TransparentShape myCircle = new TransparentShape(
new ColoredShape(
new Circle(5), "green"
), 50
);
// myCircle.resize() - does not work as TransparentShape does not inherit
System.out.println(myCircle.info());
}
}