-
-
Notifications
You must be signed in to change notification settings - Fork 131
/
Copy pathadapter_concept.py
62 lines (45 loc) · 1.31 KB
/
adapter_concept.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
62
# pylint: disable=too-few-public-methods
# pylint: disable=arguments-differ
"Adapter Concept Sample Code"
from abc import ABCMeta, abstractmethod
class IA(metaclass=ABCMeta):
"An interface for an object"
@staticmethod
@abstractmethod
def method_a():
"An abstract method A"
class ClassA(IA):
"A Sample Class the implements IA"
def method_a(self):
print("method A")
class IB(metaclass=ABCMeta):
"An interface for an object"
@staticmethod
@abstractmethod
def method_b():
"An abstract method B"
class ClassB(IB):
"A Sample Class the implements IB"
def method_b(self):
print("method B")
class ClassBAdapter(IA):
"ClassB does not have a method_a, so we can create an adapter"
def __init__(self):
self.class_b = ClassB()
def method_a(self):
"calls the class b method_b instead"
self.class_b.method_b()
# The Client
# Before the adapter I need to test the objects class to know which
# method to call.
ITEMS = [ClassA(), ClassB()]
for item in ITEMS:
if isinstance(item, ClassB):
item.method_b()
else:
item.method_a()
# After creating an adapter for ClassB I can reuse the same method
# signature as ClassA (preferred)
ITEMS = [ClassA(), ClassBAdapter()]
for item in ITEMS:
item.method_a()