【编程思想】【设计模式】【结构模式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 ...
随机推荐
- c++学习笔记(十)
返回应用类型 返回引用 1.不要返回局部变量的引用 为了验证为什么不能返回局部变量的引用,我按照所学的例题自己做了一点小测试. #include<iostream> using names ...
- .net C# 释放内存 例子
namespace myCommon{ public class SysVar { [DllImport("kernel32.dll")] public ...
- 痞子衡嵌入式:在IAR开发环境下RT-Thread工程函数重定向失效分析
大家好,我是痞子衡,是正经搞技术的痞子.今天痞子衡给大家分享的是在IAR开发环境下RT-Thread工程函数重定向失效分析. 痞子衡旧文 <在IAR下将关键函数重定向到RAM中执行的方法> ...
- MySQL统计总数就用count(*),别花里胡哨的《死磕MySQL系列 十》
有一个问题是这样的统计数据总数用count(*).count(主键ID).count(字段).count(1)那个效率高. 先说结论,不用那么花里胡哨遇到统计总数全部使用count(*). 但是有很多 ...
- 不可忽视的Dubbo线程池
问题描述 线上突然出现Dubbo超时调用,时间刚好为Consumer端设置的超时时间. 有好几个不同的接口都报超时了 第1次调用超时,第2次(或第3次)重试调用非常快(正常水平) Dubbo调用超时的 ...
- 日记啦QWWQ
随便写写 时间 :2021年11月15日 今天是在博客园创建博客的第一天,彻底放弃在CSDN中的博客,广告实在是太多了,QWQ. 来计科的第一个学期就快要结束了,期间有很多的遗憾,往后加油吧! 没什么 ...
- [atAGC045E]Fragile Balls
构造一张有向图$G=([1,n],\{(a_{i},b_{i})\})$(可以有重边和自环),定义其连通块为将其看作无向图(即边无向)后分为若干个连通块 记$in_{i}$为$i$的入度(即最终盒子中 ...
- 一文明白CDN加速是个啥
作者:IT王小二 博客:https://itwxe.com 不知不觉三个月没更新了,这三个月诸事繁忙啊!最近没那么忙了,开始恢复更新. 一.CDN简介 CDN(Content Delivery Net ...
- Electron跨平台程序破解
1. npm install asar -g 2. asar --version 如果有版本号就继续 3.找到需要解压的软件位置 在app.asar的地址输入 asar e app.asar tm ...
- vue中 has no matching end tag.
这个前端编辑体验很不好,不给自动闭合代码....