适配器模式
adapt.py
from adaptee import duck, bird class Adapter: def __init__(self, obj, method): self.obj = obj self.__dict__.update(method) def __str__(self): # print(self.obj) return str(self.obj) def main(): object = [] duck1 = duck('tanglaoya') object.append(Adapter(duck1, dict(execute=duck1.flyLow))) bird1 = bird('yingwu') object.append(Adapter(bird1, dict(execute=bird1.flyHigh))) for i in object: print('{} {}' . format(str(i), i.execute())) if __name__=='__main__': main()
adaptee.py
class duck: def __init__(self, name): self.name = name def __str__(self): return 'this duck\'s name is {}' . format(self.name) def flyLow(self): return 'fly low' class bird: def __init__(self, name): self.name = name def __str__(self): return 'this bird\'s name is {}'.format(self.name) def flyHigh(self): return 'fly high'