標籤:att int abstract 階段 mat fan 題目 ini 控制
github地址:https://github.com/cheesezh/python_design_patterns
適配器模式
適配器模式,將一個類的介面轉換成客戶希望的另外一個介面。Adapter模式使得原本由於介面不相容而不能一起工作的那些類可以一起工作[DP]。
當系統的資料和行為都正確,但是介面不符時,我們應該考慮使用適配器模式,目的就是使控制範圍之外的一個原有對象與某個介面匹配。適配器模式主要應用於希望複用一些現存的類,但是介面又與複用環境要求不一致的情況。
class Target(): """ Target類,這是客戶所期待的介面。可以是具體或抽象的類,也可以是介面。 """ def request(self): print("普通請求") class Adaptee(): """ 需要適配的類 """ def specific_request(self): print("特殊請求") class Adapter(Target): """ 適配器,通過內部封裝一個Adaptee對象,把源介面轉換成目標介面 """ def __init__(self): self.adaptee = Adaptee() def request(self): self.adaptee.specific_request() def main(): target = Adapter() target.request() main()
特殊請求
何時使用適配器模式?
想使用一個已經存在的類,但如果它的介面,也就是它的方法和你的要求不想同時,就應該考慮使用適配器模式。
對於公司內部獨立開發的系統,類和方法名的規範應當在設計之初就規定好,當介面不相同時,首先不應該考慮使用適配器,而是應該考慮通過重構統一介面。
只有在雙方都不太容易修改的時候再使用適配器模式。
但是如果設計之初,我們準備使用第三方開發組件,而這個組件的介面於我們自己的系統介面是不相同的,而我們也完全沒有必要為了迎合它而改動自己的介面,此時儘管在開發的設計階段,也就是可以考慮用適配器模式來解決介面不同的問題。
題目
用程式類比姚明到國外打NBA初期依賴翻譯的情境。
from abc import ABCMeta, abstractmethodclass Player(): __metaclass__ = ABCMeta def __init__(self, name): self.name = name @abstractmethod def attack(self): pass @abstractmethod def defense(self): pass class Forwards(Player): def attack(self): print("Forward {} attack".format(self.name)) def defense(self): print("Forward {} defense".format(self.name)) class Guards(Player): def attack(self): print("Guards {} attack".format(self.name)) def defense(self): print("Guards {} defense".format(self.name)) class ForeignCenter(): def __init__(self, name): self.name = name def jingong(self): print("Center {} jingong".format(self.name)) def fangshou(self): print("Center {} fangshou".format(self.name))class Translator(Player): def __init__(self, name): self.foreign_center = ForeignCenter(name) def attack(self): self.foreign_center.jingong() def defense(self): self.foreign_center.fangshou() forwards = Forwards("FFF")forwards.attack()guards = Guards("GGG")guards.defense()center = Translator("CCC")center.attack()center.defense()
Forward FFF attackGuards GGG defenseCenter CCC jingongCenter CCC fangshou
[Python設計模式] 第17章 程式中的翻譯官——適配器模式