【编程思想】【设计模式】【结构模式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 ...
随机推荐
- SQL注入之猫舍
第一步:先查看是否存在注入点:构造?id=1 and 1=1 回车后发现页面正常 构造?id=1 and 1=2 发现页面异常,得出结论:存在注入点 第二步:判断字段数 当输入order by 1和o ...
- 【数据结构&算法】12-线索二叉树
目录 前言 线索二叉树的概念 线索二叉树的实现 线索二叉树的寻点思路二 类双向链表参考图 参考代码 中序遍历线索化 前言 在<大话数据结构>P190 页中有一句话:其实线索二叉树,就等于是 ...
- mysql: 看不见的空符号 char(9) char(10) char(13)
在统计年度销售额时,总觉得哪里不对劲.于是找了找,对了对,试了trim,消除前后的空格,也没反应. 在崩溃的边缘,终于发现了错的原因. 原来我在录入的时候,粘贴多了其他空白符号,看不见,摸不着,啊~ ...
- 一行导出所有任意微软SQL server数据脚本-基于Python的微软官方mssql-scripter工具使用全讲解
文章标题: 一行导出所有任意微软SQL serer数据脚本-基于Python的微软官方mssql-scripter工具使用全讲解 关键字 : mssql-scripter,SQL Server 文章分 ...
- layui 如果调用 from 内嵌入的 iframe子页面方法
(人笨,占时想法的办法,不要骂,不要骂,怕了怕了,想到别的会来改的) 父页面; <%@ page language="java" contentType="text ...
- printf("%d\n",printf("%d",printf("%d",i)));
#include <stdio.h> int printf( const char *format, ... );首先 得看printf的返回类型是 int 这个函数的返回值是 你输出的位 ...
- 一文明白CDN加速是个啥
作者:IT王小二 博客:https://itwxe.com 不知不觉三个月没更新了,这三个月诸事繁忙啊!最近没那么忙了,开始恢复更新. 一.CDN简介 CDN(Content Delivery Net ...
- 微信小程序-物流api
原来用的快递100的接口有变动,现有系统上不能使用了.查看快递100提供的api,探寻微信小程序端的使用情况.有几个是比较合适的:1.跳转api(https://www.kuaidi100.com/o ...
- 7.4 k8s结合ceph rbd、cephfs实现数据的持久化和共享
1.在ceph集群中创建rbd存储池.镜像及普通用户 1.1.存储池接镜像配置 创建存储池 root@u20-deploy:~# ceph osd pool create rbd-test-pool1 ...
- APIO2020 打铁记
Day (-3) - 2020.8.11 马上要 APIO 了,不管三七二十一先刷一套历年的 APIO 再说. 花了 3h 写了 APIO2019,爆零150左右,然后查看了一下去年的分数线,Cu 1 ...