【编程思想】【设计模式】【结构模式Structural】适配器模式adapter
Python版
https://github.com/faif/python-patterns/blob/master/structural/adapter.py
#!/usr/bin/env python
# -*- coding: utf-8 -*- """
*What is this pattern about?
The Adapter pattern provides a different interface for a class. We can
think about it as a cable adapter that allows you to charge a phone
somewhere that has outlets in a different shape. Following this idea,
the Adapter pattern is useful to integrate classes that couldn't be
integrated due to their incompatible interfaces. *What does this example do? The example has classes that represent entities (Dog, Cat, Human, Car)
that make different noises. The Adapter class provides a different
interface to the original methods that make such noises. So the
original interfaces (e.g., bark and meow) are available under a
different name: make_noise. *Where is the pattern used practically?
The Grok framework uses adapters to make objects work with a
particular API without modifying the objects themselves:
http://grok.zope.org/doc/current/grok_overview.html#adapters *References:
http://ginstrom.com/scribbles/2008/11/06/generic-adapter-class-in-python/
https://sourcemaking.com/design_patterns/adapter
http://python-3-patterns-idioms-test.readthedocs.io/en/latest/ChangeInterface.html#adapter *TL;DR80
Allows the interface of an existing class to be used as another interface.
""" 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):
"""
Adapts an object by replacing methods.
Usage:
dog = Dog
dog = Adapter(dog, dict(make_noise=dog.bark)) >>> objects = []
>>> dog = Dog()
>>> print(dog.__dict__)
{'name': 'Dog'}
>>> objects.append(Adapter(dog, make_noise=dog.bark))
>>> print(objects[0].original_dict())
{'name': 'Dog'}
>>> cat = Cat()
>>> objects.append(Adapter(cat, make_noise=cat.meow))
>>> human = Human()
>>> objects.append(Adapter(human, make_noise=human.speak))
>>> car = Car()
>>> car_noise = lambda: car.make_noise(3)
>>> objects.append(Adapter(car, make_noise=car_noise)) >>> for obj in objects:
... print('A {} goes {}'.format(obj.name, obj.make_noise()))
A Dog goes woof!
A Cat goes meow!
A Human goes 'hello'
A Car goes vroom!!!
""" 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() ### OUTPUT ###
# {'name': 'Dog'}
# {'make_noise': <bound method Dog.bark of <__main__.Dog object at 0x7f631ba3fb00>>, 'obj': <__main__.Dog object at 0x7f631ba3fb00>}
# {'name': 'Dog'}
# A Dog goes woof!
# A Cat goes meow!
# A Human goes 'hello'
# A Car goes vroom!!!
Python转载版
【编程思想】【设计模式】【结构模式Structural】适配器模式adapter的更多相关文章
- 七个结构模式之适配器模式(Adapter Pattern)
定义: 将一个接口转换为客户需要的另外一个接口,使接口不兼容的类型可以一起工作,也被称为包装器模式(Wrapper Patern). 结构图: Target:目标抽象类,客户所需要的接口. Adapt ...
- 设计模式(五)适配器模式Adapter(结构型)
设计模式(五)适配器模式Adapter(结构型) 1. 概述: 接口的改变,是一个需要程序员们必须(虽然很不情愿)接受和处理的普遍问题.程序提供者们修改他们的代码;系统库被修正;各种程序语言以及相 ...
- 七、适配器(Adapter)模式--结构模式(Structural Pattern)
适配器模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作. 类的 Adapter模式的结构: 类适配器类图: 由图中可以看出,Adaptee ...
- 设计模式(三)-- 适配器模式(Adapter)
适配器模式(Adapter) 考虑一个记录日志的应用,由于用户对日志记录的要求很高,使得开发人员不能简单地采用一些已有的日志工具或日志框架来满足用户的要求,而需要按照用户的要求重新开发新的日志管理系统 ...
- 【编程思想】【设计模式】【结构模式Structural】代理模式Proxy
Python版 https://github.com/faif/python-patterns/blob/master/structural/proxy.py #!/usr/bin/env pytho ...
- 【编程思想】【设计模式】【结构模式Structural】MVC
Python版 https://github.com/faif/python-patterns/blob/master/structural/mvc.py #!/usr/bin/env python ...
- 【编程思想】【设计模式】【结构模式Structural】front_controller
Python版 https://github.com/faif/python-patterns/blob/master/structural/front_controller.py #!/usr/bi ...
- 【编程思想】【设计模式】【结构模式Structural】享元模式flyweight
Python版 https://github.com/faif/python-patterns/blob/master/structural/flyweight.py #!/usr/bin/env p ...
- 【编程思想】【设计模式】【结构模式Structural】门面模式/外观模式Facade
Python版 https://github.com/faif/python-patterns/blob/master/structural/facade.py #!/usr/bin/env pyth ...
随机推荐
- 性能工具之代码级性能测试工具ContiPerf
前言 做性能的同学一定遇到过这样的场景:应用级别的性能测试发现一个操作的响应时间很长,然后要花费很多时间去逐级排查,最后却发现罪魁祸首是代码中某个实现低效的底层算法.这种自上而下的逐级排查定位的方法, ...
- vue修改启动的端口和host
打开vue项目(dev) dev/config/ 路径修改index.js文件 然后对host和pord修改指定的即可 host: 'localhost', // can be overwritten ...
- rabbitMQ报错:Caused by: com.rabbitmq.client.ShutdownSignalException: connection error; protocol method:
1.输入的机器的 IP:15672进入Raabitmq的登陆管理界面 点击admin,进去点击set permission ok, 在运行应该就不会包这个错了
- Python-Unittest多线程执行用例
前言 假设执行一条脚本(.py)用例一分钟,那么100个脚本需要100分钟,当你的用例达到一千条时需要1000分钟,也就是16个多小时... 那么如何并行运行多个.py的脚本,节省时间呢?这就用到多线 ...
- element ui tree回显 setCheckedNodes,setCheckedKeys,setChecked等函数报undefined问题
在写项目的时候,需要用到tree组件进行回显来进行权限控制: 在回显过程中使用回显函数会报报undefined, 这时只需要给该函数包裹一层nextTick方法就行了, 在回显过程中我们有可能使用半选 ...
- python实现直方图的应用
目录: (一)调节图片对比度(均衡化) (1)全局直方图均衡化------equalizeHist (2)自适应的局部的直方图均衡化------createCLAHE (二)图片的相似度比较 (三)直 ...
- [noi34]palindrome
分割实际上就是不断地从两端取出一样的一段,并对剩下的串进行分割.下面我们来证明一下每一次贪心取出最短一段的正确性: 考虑两种分割方式,分别表示成S=A+B+A和S=C+D+C,其中A就是最短的一段,那 ...
- patch增量更新
- 使用idea创建Kotlin项目
1.打开idea 2.选择项目方式: 3.nest 4.创建文件名 4.finish 看这目录结构和java没什么区别 5.在src目录下新建一个Kotlin文件 fun main(args:} fu ...
- 洛谷 P7879 -「SWTR-07」How to AK NOI?(后缀自动机+线段树维护矩乘)
洛谷题面传送门 orz 一发出题人(话说我 AC 这道题的时候,出题人好像就坐在我的右侧呢/cy/cy) 考虑一个很 naive 的 DP,\(dp_i\) 表示 \([l,i]\) 之间的字符串是否 ...