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()))
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()))
def main(): objects = [Computer('Asus')] # # objects is a list, and a receiver for Adapter # print(type(objects)) 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()))
def main(): objects = [Computer('IBM')] synth = Synthesizer('moog') objects.append(Adapter( synth, dict(execute=synth.play))) #这里是把其他类的相应的方法指定到execute方法上 human = Human('kellan') objects.append(Adapter(human, dict(execute=human.speak))) print(objects) for i in objects: #print(i.name) print('{} {}'.format(str(i), i.execute()))
def main(): # objects 容纳着所有对象, 兼容Computer的对象可以直接append objects = [Computer('Asus')] synth = Synthesizer('moog') # 不兼容Computer的对象需要使用Adapter来适配一下再添加到objects中 objects.append(Adapter(synth, dict(execute=synth.play))) human = Human('Bob') objects.append(Adapter(human, dict(execute=human.speak))) # 最终所有对象都可以调用execute方法, 而无需关心类之间的接口差异 for i in objects: print('{} {}'.format(str(i), i.execute())) for i in objects: print(i.name)
def execute(self): return 'executes a program' class Adapter(object): """ implement of adapter """ def __init__(self, obj, adapted_method): """ add other method in __dict__ :param obj: :param adapted_method: """ self.obj = obj self.__dict__.update(adapted_method) def __str__(self): return str(self.obj) if __name__ == '__main__': objects = [] objects.append(Computer('EdwardChou')) syth = Synthesizer('Dreamer') objects.append(Adapter(syth, dict(execute=syth.play))) human = Human('Birdman') objects.append(Adapter(human, dict(execute=human.speak))) for i in objects: print('{} {}'.format(str(i), i.execute()))