-
Notifications
You must be signed in to change notification settings - Fork 32
/
bridge.py
61 lines (44 loc) · 1.15 KB
/
bridge.py
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
"""
Bridge
- A mechanism that decouples an interface (hierarchy) from an implementation
(hierarchy)
Motivation
- Prevents a 'Cartesian product' complexity explosion
"""
from abc import ABC
class Renderer(ABC):
def render_circle(self, radius):
pass
# render square
class VectorRenderer(Renderer):
def render_circle(self, radius):
print(f'Drawing a circle of radius {radius}')
class RasterRenderer(Renderer):
def render_circle(self, radius):
print(f'Drawing pixels for a circle of radius {radius}')
class Shape:
def __init__(self, renderer):
self.renderer = renderer
def draw(self):
pass
def resize(self, factor):
pass
class Circle(Shape):
def __init__(self, renderer, radius):
super().__init__(renderer)
self.radius = radius
def draw(self):
# bridge
self.renderer.render_circle(self.radius)
def resize(self, factor):
self.radius *= factor
RASTER = RasterRenderer()
VECTOR = VectorRenderer()
CIRCLE = Circle(VECTOR, 5)
CIRCLE.draw()
CIRCLE.resize(2)
CIRCLE.draw()
CIRCLE = Circle(RASTER, 5)
CIRCLE.draw()
CIRCLE.resize(2)
CIRCLE.draw()