您好,登錄后才能下訂單哦!
Python適配器模式,代碼,思考等
# -*- coding: utf-8 -*- # author:baoshan class Computer: def __init__(self, name): self.name = name def __str__(self): return 'the {} computer'.format(self.name) def execute(self): return 'executes a program' class Synthesizer: def __init__(self, name): self.name = name def __str__(self): return 'the {} synthesizer'.format(self.name) def play(self): return 'is playing an electronic song' class Human: def __init__(self, name): self.name = name def __str__(self): return '{} the human'.format(self.name) def speak(self): return 'says hello' 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 = [Computer('Asus')] synth = Synthesizer('moog') objects.append(Adapter(synth, dict(execute=synth.play))) human = Human('Bob') objects.append(Adapter(human, dict(execute=human.speak))) for i in objects: print('{} {}'.format(str(i), i.execute())) if __name__ == '__main__': main()
代碼輸出:
the Asus computer executes a program the moog synthesizer is playing an electronic song Bob the human says hello
------------------------------------------------------------------------------------------
我們設法使得Human和Synthesizer類與客戶端所期望的接口兼容,且無需改變它們的源代碼。這太棒了!
這里有一個為你準備的挑戰性練習,當前的實現有一個問題,當所有類都有一個屬性name時,以下代碼會運行失敗。
for i in objects: print('{}'.format(i.name))
首先想想這段代碼為什么會失敗?雖然從編碼的角度來看這是有意義的,但對于客戶端代碼來說毫無意義,客戶端不應該關心“適配了什么”和“什么沒有被適配”這類細節。我們只是想提供一個統一的接口。該如何做才能讓這段代碼生效?
思考一下如何將未適配部分委托給包含在適配器類中的對象。
答案如下:
將適配器類更改如下,增加一行代碼
class Adapter: def __init__(self, obj, adapted_methods): self.obj = obj self.__dict__.update(adapted_methods) self.name = obj.name def __str__(self): return str(self.obj)
然后在main函數中獲取對應的name,如下
def main(): objects = [Computer('Asus')] synth = Synthesizer('moog') objects.append(Adapter(synth, dict(execute=synth.play))) human = Human('Bob') objects.append(Adapter(human, dict(execute=human.speak))) for i in objects: print('{} {}'.format(str(i), i.execute())) print('{}'.format(i.name)) if __name__ == '__main__': main()
輸出結果如下:
the Asus computer executes a program Asus the moog synthesizer is playing an electronic song moog Bob the human says hello Bob
參考自:《精通Python設計模式》
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。