使用適配器模式使用兩個或是多個不兼容的接口兼容。在不修改不兼容代碼的情況下使用適配器模式實現(xiàn)接口一致性。通過Adapter 類實現(xiàn)。
例子: 一個俱樂部類Club,藝術(shù)加被請到俱樂部在表演節(jié)目: organize_performance()
Musician類 play()? 方法? Dancer 類主要是dance() 方法執(zhí)行? (external.py)?
外部模塊導入(adapter.py)創(chuàng)建一個通用的? Adapter類調(diào)整不兼容的對象。
?__init__() 方法的obj 參數(shù)是需要修改的對象,adapted_methods 是一個字典,包含與客戶端調(diào)用的方法和應該調(diào)用方法匹配的鍵值對。
chapter04/external.py
class Musician:
def __init__(self, name):
self.name = name
def __str__(self):
return f'the musician {self.name}'
def play(self):
return 'plays music'
class Dancer:
def __init__(self, name):
self.name = name
def __str__(self):
return f'the dancer {self.name}'
def dance(self):
return 'does a dance performance'
chapter04/adapter.py文章來源:http://www.zghlxwxcb.cn/news/detail-741597.html
from external import Musician, Dancer
class Club:
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 Adapter:
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) # 設(shè)置調(diào)用方法統(tǒng)一organize_event
elif hasattr(obj, 'dance'):
adapted_methods = dict(organize_event=obj.dance) # 設(shè)置調(diào)用方法統(tǒng)一organize_event
# referencing the adapted object here
obj = Adapter(obj, adapted_methods)
print(f' 輸出 {obj} {obj.organize_event()}') # 調(diào)用統(tǒng)一方法
if __name__ == "__main__":
main()
?輸出 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文章來源地址http://www.zghlxwxcb.cn/news/detail-741597.html
到了這里,關(guān)于python設(shè)計模式4:適配器模式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!