設計模式--適配器

做用:適配器模式能夠將不統一的接口統一到同一種形式,方便管理。
應用場景:根據一種需求寫的各類類,定義好各個函數接口,可能被其餘後加功能體系徵用
,產>生函數不統一的現象,這時候就能夠用適配器模式進行歸一。目的是保證數據源,功能 > 的統一
class Adaptee:

    def specific_request(self):

        return 'Adaptee'



class Adapter:

    def __init__(self, adaptee):

        self.adaptee = adaptee



    def request(self):

        return self.adaptee.specific_request()



client = Adapter(Adaptee())

print(client.request())



# --------- Second example (by Alex Martelli)------------



class UppercasingFile:

    def __init__(self, *a, **k):

        self.f = file(*a, **k)

    def write(self, data):

        self.f.write(data.upper())

    def __getattr__(self, name):

        return getattr(self.f, name)
相關文章
相關標籤/搜索