-
Notifications
You must be signed in to change notification settings - Fork 3
/
adapter.py
57 lines (38 loc) · 1.06 KB
/
adapter.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
from abc import abstractmethod
# My Interface
class MyInterface:
def __init__(self):
pass
@abstractmethod
def get_voltage(self):
pass
class MySocket(MyInterface):
def __init__(self, name):
self.name = name
def get_voltage(self):
return 110
# Other Interface (from other library, for example)
class OtherInterface:
def __init__(self):
pass
@abstractmethod
def get_volts(self):
pass
class StrangeSocket(OtherInterface):
def __init__(self, dummy_var):
self.dummy_var = dummy_var
def get_volts(self):
return "220"
# Adapter Pattern
class Adapter(MyInterface):
def __init__(self, other_interface):
self.other_interface = other_interface
def get_voltage(self):
volts = self.other_interface.get_volts()
return int(volts)
my = MySocket("My Socket")
print(" MySocket:", my.get_voltage())
other = StrangeSocket("dummy value")
print("StrangeSocket:", other.get_volts())
adapter = Adapter(other)
print(" Adapter:", adapter.get_voltage())