设计模式-适配器模式-adapter-python
2017-08-10 00:59
471 查看
def
将一个类的接口变换成客户端所期待的另一种接口, 从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。usage
● 适配器模式可以让两个没有任何关系的类在一起运行, 只要适配器这个角色能够搞定他们就成。● 增加了类的透明性 我们访问的Target目标角色, 但是具体的实现都委托给了源角色, 而这些对高
层次模块是透明的, 也是它不需要关心的。
● 提高了类的复用度 当然了, 源角色在原有的系统中还是可以正常使用, 而在目标角色中也可以充当新的演员。
● 灵活性非常好 某一天, 突然不想要适配器, 没问题, 删除掉这个适配器就可以了, 其他的代码都不用修改, 基本上就类似一个灵活的构件, 想用就用, 不想就卸载
code
class Dog(object): def __init__(self): self.name = "Dog" def bark(self): return "woof!" class Cat(object): def __init__(self): self.name = "Cat" def meow(self): return "meow!" class Human(object): def __init__(self): self.name = "Human" def speak(self): return "'hello'" class Car(object): def __init__(self): self.name = "Car" def make_noise(self, octane_level): return "vroom{0}".format("!" * octane_level) class Adapter(object): def __init__(self, obj, **adapted_methods): """We set the adapted methods in the object's dict""" self.obj = obj self.__dict__.update(adapted_methods) def __getattr__(self, attr): """All non-adapted calls are passed to the object""" return getattr(self.obj, attr) def original_dict(self): """Print original object dict""" return self.obj.__dict__ def main(): objects = [] dog = Dog() print(dog.__dict__) objects.append(Adapter(dog, make_noise=dog.bark)) print(objects[0].__dict__) print(objects[0].original_dict()) cat = Cat() objects.append(Adapter(cat, make_noise=cat.meow)) human = Human() objects.append(Adapter(human, make_noise=human.speak)) car = Car() objects.append(Adapter(car, make_noise=lambda: car.make_noise(3))) for obj in objects: print("A {0} goes {1}".format(obj.name, obj.make_noise())) if __name__ == "__main__": main()
相关文章推荐
- 研磨设计模式解析及python代码实现——(三)适配器模式(Adapter)
- JAVA--适配器模式(Adapter)--设计模式六
- 设计模式-适配器模式(Adapter)
- 设计模式深入学习---Adapter 适配器模式(结构型模式)
- 设计模式读书笔记之适配器模式(Adapter)
- 解读设计模式----适配器模式(Adapter Pattern),麻雀飞上枝头真能成凤凰?
- 乐在其中设计模式(C#) - 适配器模式(Adapter Pattern)
- 设计模式之适配器模式(Adapter)
- Java经典设计模式-结构型模式-适配器模式(Adapter)
- 设计模式6:Adapter Pattern (适配器模式)
- 【Unity与23种设计模式】适配器模式(Adapter)
- 设计模式-----适配器模式(Adapter)
- 【JAVA】设计模式之适配器模式(Adapter模式)的使用分析
- (二)二十三中设计模式之我见-----------------适配器模式(Adapter Pattern)
- java23种常用设计模式之适配器模式(Adapter)
- 设计模式——适配器模式(Adapter)
- .Net设计模式 Adapter 适配器模式(结构型模式)Adapter Pattern
- 深入浅出设计模式——适配器模式(Adapter Pattern)
- 23种设计模式(6)_结构型_适配器模式(Adapter Pattern)
- 深入浅出设计模式-007:适配器模式(Adapter Pattern)