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的更多相关文章

  1. 七个结构模式之适配器模式(Adapter Pattern)

    定义: 将一个接口转换为客户需要的另外一个接口,使接口不兼容的类型可以一起工作,也被称为包装器模式(Wrapper Patern). 结构图: Target:目标抽象类,客户所需要的接口. Adapt ...

  2. 设计模式(五)适配器模式Adapter(结构型)

      设计模式(五)适配器模式Adapter(结构型) 1. 概述: 接口的改变,是一个需要程序员们必须(虽然很不情愿)接受和处理的普遍问题.程序提供者们修改他们的代码;系统库被修正;各种程序语言以及相 ...

  3. 七、适配器(Adapter)模式--结构模式(Structural Pattern)

    适配器模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本接口不匹配而无法在一起工作的两个类能够在一起工作. 类的 Adapter模式的结构: 类适配器类图: 由图中可以看出,Adaptee ...

  4. 设计模式(三)-- 适配器模式(Adapter)

    适配器模式(Adapter) 考虑一个记录日志的应用,由于用户对日志记录的要求很高,使得开发人员不能简单地采用一些已有的日志工具或日志框架来满足用户的要求,而需要按照用户的要求重新开发新的日志管理系统 ...

  5. 【编程思想】【设计模式】【结构模式Structural】代理模式Proxy

    Python版 https://github.com/faif/python-patterns/blob/master/structural/proxy.py #!/usr/bin/env pytho ...

  6. 【编程思想】【设计模式】【结构模式Structural】MVC

    Python版 https://github.com/faif/python-patterns/blob/master/structural/mvc.py #!/usr/bin/env python ...

  7. 【编程思想】【设计模式】【结构模式Structural】front_controller

    Python版 https://github.com/faif/python-patterns/blob/master/structural/front_controller.py #!/usr/bi ...

  8. 【编程思想】【设计模式】【结构模式Structural】享元模式flyweight

    Python版 https://github.com/faif/python-patterns/blob/master/structural/flyweight.py #!/usr/bin/env p ...

  9. 【编程思想】【设计模式】【结构模式Structural】门面模式/外观模式Facade

    Python版 https://github.com/faif/python-patterns/blob/master/structural/facade.py #!/usr/bin/env pyth ...

随机推荐

  1. IDEA中Update resources和Update classes and resources、Redeploy、Restart server的区别

    选项 描述 update resources 所有更改的资源都会更新(HTML,JSP,JavaScript,CSS和图像文件) update classes and resources 更改的资源将 ...

  2. 几个你不知道的dubbo注册中心细节

    你会正确配置backup地址吗? 在配置dubbo注册中心时,一般会这样写 dubbo.registry.protocol=zookeeper dubbo.registry.address=127.0 ...

  3. Dao、Controller、Service三层的结构划分

     Java Web基础--Controller+Service +Dao三层的功能划分(摘取自网络)1. Controller/Service/DAO简介:      Controller是管理业务( ...

  4. Three.js实现脸书元宇宙3D动态Logo

    背景 Facebook 近期将其母公司改名为 Meta,宣布正式开始进军 元宇宙 领域.本文主要讲述通过 Three.js + Blender 技术栈,实现 Meta 公司炫酷的 3D 动态 Logo ...

  5. [loj2504]小H爱染色

    以下考虑直接对所有$F(A)$求和,并给出两种做法-- 做法1: 枚举答案$A$,对应方案数为${n-A\choose m}^{2}-{n-A-1\choose m}^{2}$,即答案为$\sum_{ ...

  6. [luogu5537]系统设计

    考虑哈希,令$h[x]$表示根到$x$路径的哈希值,那么有$h[x]+hash(l,r)=h[ans]$ 考虑用线段树维护$a_{i}$的区间哈希值,并用map去找到对应的$ans$ 但还有一个问题, ...

  7. [loj3342]制作菜品

    当$n-1\le m$,不妨令$d_{1}\le d_{2}\le...\le d_{n}$,则$(n-1)k\le mk=\sum_{i=1}^{n}d_{i}\le d_{1}+(n-1)d_{n ...

  8. MS17-010漏洞利用

    MS17-010漏洞利用 1.安装虚拟机win7 x64,实现利用ms17-010实现对其win7 x64主机开始渗透,查看该主机信息,打开远程桌面,抓取用户名和密码并破译,创建一个 : 学号.txt ...

  9. 「后端小伙伴来学前端了」Vuex进阶操作,让你的代码更加高效(简称如何学会偷懒 【手动狗头】)

    学妹手机里的美照 前言 前一篇写了Vuex基本使用,用起来还稍稍有些繁琐,代码有很多 冗余的地方,这篇就带着大家用更简单的方式来使用Vuex(其实就是怎么更好的偷懒,用更少的代码来完之前的事情) 进入 ...

  10. 记一次 .NET 某智能服装智造系统 内存泄漏分析

    一:背景 1. 讲故事 上个月有位朋友找到我,说他的程序出现了内存泄漏,不知道如何进一步分析,截图如下: 朋友这段话已经说的非常言简意赅了,那就上 windbg 说话吧. 二:Windbg 分析 1. ...