《精通Python设计模式》学习结构型之适配器模式
Posted aguncn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《精通Python设计模式》学习结构型之适配器模式相关的知识,希望对你有一定的参考价值。
大名鼎鼎~~
在兼容老系统和其它系统外调用时,用得着~
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‘
from extenrnal import Synthesizer, Human 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 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(‘Intel‘)] 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()
以上是关于《精通Python设计模式》学习结构型之适配器模式的主要内容,如果未能解决你的问题,请参考以下文章