-
Notifications
You must be signed in to change notification settings - Fork 2
/
Bridge.java
110 lines (93 loc) · 2.43 KB
/
Bridge.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
109
110
// Bridge
package structural.bridge;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
// Shape -> Circle, Square
// Rendering -> Vector, Raster
// Direct solution: VectorCircleRenderer, VectorSquareRenderer,RasterCircleRenderer....
interface Renderer
{
void renderCircle(float radius);
}
class VectorRenderer implements Renderer
{
@Override
public void renderCircle(float radius) {
System.out.println("Drawing a circle of radius "
+ radius);
}
}
class RasterRenderer implements Renderer
{
@Override
public void renderCircle(float radius) {
System.out.println("Drawing pixels for a circle "
+ "of radius " + radius);
}
}
// Bridge here
abstract class Shape
{
protected Renderer renderer;
public Shape(Renderer renderer) {
this.renderer = renderer;
}
public abstract void draw();
public abstract void resize(float factor);
}
class Circle extends Shape
{
public float radius;
// Using a DI framework, you have a single point to determine what type
// of renderer you want
@Inject
public Circle(Renderer renderer) {
super(renderer);
}
// Circle is dependent upon the renderer
public Circle(Renderer renderer, float radius) {
super(renderer);
this.radius = radius;
}
@Override
public void draw()
{
renderer.renderCircle(radius);
}
@Override
public void resize(float factor)
{
radius *= factor;
}
}
class ShapeModule extends AbstractModule
{
@Override
protected void configure()
{
// When someone requests a Renderer to be injected
// we make a new instance of VectorRenderer
bind(Renderer.class).to(VectorRenderer.class);
}
}
class BridgeDemo
{
public static void main(String[] args) {
// Injecting dependencies by hand
// RasterRenderer raster = new RasterRenderer();
// VectorRenderer vector = new VectorRenderer();
// Circle circle = new Circle(vector, 5);
// circle.draw();
// circle.resize(2);
// circle.draw();
// Using google guice
Injector injector = Guice.createInjector(new ShapeModule());
Circle instance = injector.getInstance(Circle.class);
instance.radius = 3;
instance.draw();
instance.resize(2);
instance.draw();
}
}