精通Python设计模式第二版 第 4 章 适配器模式 学习笔记
适配器模式是一种结构型设计模式,能帮助我们使两个不兼容的接口兼容。
假设我们想使用function_a()作为接口,但是只有function_b(),则可以使用适配器将function_b()转换(适配)为function_a()
假设我们有这样一个需求:一个俱乐部活动,主要是通过聘请有才华的艺术家,组织演出和活动,来为客户提供娱乐活动
organize_performance()方法是俱乐部可以执行的主要操作
class Club():
"""
Club :
Attributes:
"""
def __init__(self, name):
self.name = name
def __str__(self):
return f'the club {self.name}'
def organize_event(self):
return 'hires an artist to perform for the people'
在Musician类中,主要动作有play()方法执行。在Dance类中,主要动作有dance()方法执行
class Musician():
"""
Musician :
Attributes:
"""
def __init__(self, name):
self.name = name
def __str__(self):
return f'the musician {self.name}'
def play(self):
return 'plays music'
class Dancer():
"""
Dancer :
Attributes:
"""
def __init__(self, name):
self.name = name
def __str__(self):
return f'the dancer {self.name}'
def dance(self):
return 'does a dance performance'
它允许我们将具有不同接口的许多对象调整为一个统一的接口
adapted_method是一个字典,它包含与客户端调用的方法匹配的键值对
class Adapter():
"""
Adapter :
Attributes:
"""
def __init__(self, obj, adapted_methods):
self.obj = obj
self.__dict__.update(adapted_methods)
def __str__(self):
return str(self.obj)
当处理不同的类实例是,有如下两种情况
def main():
objects = [Club('Jazz Cafe'), Musician('Roy Ayers'), Dancer('Shane Sparks')]
for obj in objects:
if hasattr(obj, 'play') or hasattr(obj, 'dance'):
if hasattr(obj, 'play'):
adapted_methods = dict(organize_event=obj.play)
elif hasattr(obj, 'dance'):
adapted_methods = dict(organize_event=obj.dance)
# 此处指被适配的对象
obj = Adapter(obj, adapted_methods)
print(f'{obj} {obj.organize_event()}')
获得打印如下
the club Jazz Cafe hires an artist to perform for the people
the musician Roy Ayers plays music
the dancer Shane Sparks does a dance performance
class Club():
"""
Club :
Attributes:
"""
def __init__(self, name):
self.name = name
def __str__(self):
return f'the club {self.name}'
def organize_event(self):
return 'hires an artist to perform for the people'
class Musician():
"""
Musician :
Attributes:
"""
def __init__(self, name):
self.name = name
def __str__(self):
return f'the musician {self.name}'
def play(self):
return 'plays music'
class Dancer():
"""
Dancer :
Attributes:
"""
def __init__(self, name):
self.name = name
def __str__(self):
return f'the dancer {self.name}'
def dance(self):
return 'does a dance performance'
class Adapter():
"""
Adapter :
Attributes:
"""
def __init__(self, obj, adapted_methods):
self.obj = obj
self.__dict__.update(adapted_methods)
def __str__(self):
return str(self.obj)
def main():
objects = [Club('Jazz Cafe'), Musician('Roy Ayers'), Dancer('Shane Sparks')]
for obj in objects:
if hasattr(obj, 'play') or hasattr(obj, 'dance'):
if hasattr(obj, 'play'):
adapted_methods = dict(organize_event=obj.play)
elif hasattr(obj, 'dance'):
adapted_methods = dict(organize_event=obj.dance)
# 此处指被适配的对象
obj = Adapter(obj, adapted_methods)
print(f'{obj} {obj.organize_event()}')
if __name__ == '__main__':
main()