Repository navigation
Expand file tree
/
Copy pathbridge.py
More file actions
64 lines (46 loc) · 1.64 KB
/
Copy pathbridge.py
File metadata and controls
64 lines (46 loc) · 1.64 KB
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
"""
Bridge — vary an abstraction and its implementation independently
A `Remote` is the abstraction; a `Device` (TV or Radio) is the
implementation. The remote holds a device and talks to it through a
small interface, so the two hierarchies grow on their own axes: add an
`AdvancedRemote` without touching any device, add a `Speaker` without
touching any remote.
Compare with the procedural Python version, where every pairing is a
class — `TVRemote`, `RadioRemote`, `AdvancedTVRemote`, ... — and the
count explodes:
class AdvancedTVRemote: ...
class AdvancedRadioRemote: ...
POOP keeps the two sides apart and bridges them by holding a
reference. Remotes and devices combine at runtime, not in the class
list.
Smalltalk:
Remote>>volumeUp
volume := volume + 10.
^device setVolume: volume
AdvancedRemote>>mute
^device setVolume: 0
"""
# Implementation hierarchy — devices.
class TV:
def set_volume(self, percent):
return "TV volume now " + percent.repr()
class Radio:
def set_volume(self, percent):
return "Radio volume now " + percent.repr()
# Abstraction hierarchy — remotes, each holding a device.
class Remote:
def __init__(self, device):
self._device = device
self._volume = 0
def volume_up(self):
self._volume = self._volume + 10
return self._device.set_volume(self._volume)
class AdvancedRemote(Remote):
def mute(self):
self._volume = 0
return self._device.set_volume(0)
Remote(TV()).volume_up().print()
Remote(Radio()).volume_up().print()
advanced = AdvancedRemote(TV())
advanced.volume_up().print()
advanced.mute().print()