|
| 1 | +# https://refactoring.guru/design-patterns/bridge |
| 2 | + |
| 3 | +from abc import ABCMeta, abstractmethod |
| 4 | + |
| 5 | + |
| 6 | +class EntertainmentDevice(metaclass=ABCMeta): |
| 7 | + def __init__(self): |
| 8 | + self.volume_level = 0 |
| 9 | + |
| 10 | + def press_button_left(self): |
| 11 | + self.volume_level -= 1 |
| 12 | + print('Volume is decreased') |
| 13 | + |
| 14 | + def press_button_right(self): |
| 15 | + self.volume_level += 1 |
| 16 | + print('Volume is increased') |
| 17 | + |
| 18 | + @abstractmethod |
| 19 | + def press_button_up(self): |
| 20 | + pass |
| 21 | + |
| 22 | + @abstractmethod |
| 23 | + def press_button_down(self): |
| 24 | + pass |
| 25 | + |
| 26 | + |
| 27 | +class TVDevice(EntertainmentDevice): |
| 28 | + def press_button_up(self): |
| 29 | + print("next channel") |
| 30 | + |
| 31 | + def press_button_down(self): |
| 32 | + print("previous channel") |
| 33 | + |
| 34 | + |
| 35 | +class DVDDevice(EntertainmentDevice): |
| 36 | + def press_button_up(self): |
| 37 | + print("next track") |
| 38 | + |
| 39 | + def press_button_down(self): |
| 40 | + print("previous track") |
| 41 | + |
| 42 | + |
| 43 | +class Remote(): |
| 44 | + def __init__(self, device): |
| 45 | + self.device = device |
| 46 | + |
| 47 | + def press_button_left(self): |
| 48 | + self.device.press_button_left() |
| 49 | + |
| 50 | + def press_button_right(self): |
| 51 | + self.device.press_button_right() |
| 52 | + |
| 53 | + def press_button_up(self): |
| 54 | + self.device.press_button_up() |
| 55 | + |
| 56 | + def press_button_down(self): |
| 57 | + self.device.press_button_down() |
| 58 | + |
| 59 | + @abstractmethod |
| 60 | + def press_button_middle(self): |
| 61 | + pass |
| 62 | + |
| 63 | + |
| 64 | +class TVRemote(Remote): |
| 65 | + def __init__(self, device): |
| 66 | + super(TVRemote, self).__init__(device) |
| 67 | + |
| 68 | + def press_button_middle(self): |
| 69 | + print("TV was muted") |
| 70 | + |
| 71 | + |
| 72 | +class DVDRemote(Remote): |
| 73 | + def __init__(self, device): |
| 74 | + super(DVDRemote, self).__init__(device) |
| 75 | + |
| 76 | + def press_button_middle(self): |
| 77 | + print("DVD was paused") |
| 78 | + |
| 79 | + |
| 80 | +device = int(input( |
| 81 | + "Which kind of device? 1.TV 2.DVD :")) |
| 82 | +remote = int(input( |
| 83 | + "Which kind of remote? 1.TV remote 2.DVD remote :")) |
| 84 | + |
| 85 | +if device == 1: |
| 86 | + device = TVDevice() |
| 87 | +else: |
| 88 | + device = DVDDevice() |
| 89 | + |
| 90 | +if remote == 1: |
| 91 | + remote = TVRemote(device) |
| 92 | +else: |
| 93 | + remote = DVDRemote(device) |
| 94 | + |
| 95 | +remote.press_button_left() |
| 96 | +remote.press_button_right() |
| 97 | +remote.press_button_up() |
| 98 | +remote.press_button_down() |
| 99 | +remote.press_button_middle() |
0 commit comments