php网站后台搭建,物流公司模板wordpress,黄冈免费网站推广平台汇总,wordpress heroku使用适配器模式使用两个或是多个不兼容的接口兼容。在不修改不兼容代码的情况下使用适配器模式实现接口一致性。通过Adapter 类实现。
例子#xff1a; 一个俱乐部类Club#xff0c;艺术加被请到俱乐部在表演节目#xff1a; organize_performance#xff08;#xff09;…使用适配器模式使用两个或是多个不兼容的接口兼容。在不修改不兼容代码的情况下使用适配器模式实现接口一致性。通过Adapter 类实现。
例子 一个俱乐部类Club艺术加被请到俱乐部在表演节目 organize_performance
Musician类 play() 方法 Dancer 类主要是dance() 方法执行 external.py
外部模块导入adapter.py创建一个通用的 Adapter类调整不兼容的对象。 __init__() 方法的obj 参数是需要修改的对象adapted_methods 是一个字典包含与客户端调用的方法和应该调用方法匹配的键值对。
chapter04/external.py
class Musician: def __init__(self, name): self.name namedef __str__(self): return fthe musician {self.name} def play(self): return plays music class Dancer: def __init__(self, name): self.name name def __str__(self): return fthe dancer {self.name} def dance(self): return does a dance performance
chapter04/adapter.py
from external import Musician, Dancerclass Club: def __init__(self, name): self.name name def __str__(self): return fthe 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_eventobj.play) # 设置调用方法统一organize_eventelif hasattr(obj, dance): adapted_methods dict(organize_eventobj.dance) # 设置调用方法统一organize_event# referencing the adapted object hereobj Adapter(obj, adapted_methods)print(f 输出 {obj} {obj.organize_event()}) # 调用统一方法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