-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathadapter.py
54 lines (44 loc) · 1.26 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
#!/usr/bin/python
# -*- coding : utf-8 -*-
"""
brief:
Adapter.
Convert the interface of a class into
another interface clients expect.Adapter lets classes
work together that couldn't otherwise because of
incompatible interfaces.
References:
https://github.com/faif/python-patterns/blob/master/structural/adapter.py
"""
# Adaptee.
class Dog(object):
def __init__(self):
self.name = "Dog"
def bark(self):
return "woof!"
class Cat(object):
def __init__(self):
self.name = "Cat"
def meow(self):
return "meow!"
# Adapter.
class Adapter(object):
def __init__(self, obj, **adapted_methods):
"""We set the adapted methods in the object's dict"""
self.obj_bak = obj
self.__dict__.update(adapted_methods)
def original_dict(self):
return self.obj_bak.__dict__
if __name__ == "__main__":
objects = []
dog = Dog()
print(dog.__dict__)
objects.append(Adapter(dog, make_noise=dog.bark))
print(objects[0].__dict__)
print(objects[0].original_dict())
cat = Cat()
objects.append(Adapter(cat, make_noise=cat.meow))
# The function make_noise is converted from
# the second input parameter of the constructor of Adapter.
for obj in objects:
print("A {0} goes {1}".format(obj.obj_bak.name, obj.make_noise()))