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. 【Python+postman接口自动化测试】(3)什么是接口测试?

    什么是接口测试? 接口测试是测试系统组件间接口的一种测试.接口测试主要用于检测外部系统与系统之间以及内部各个子系统之间的交互点.测试的重点是要检查数据的交换.传递和控制管理过程,以及系统间的相互逻辑依 ...

  2. NodeJs创建一个简单的服务器

    步骤: 1 //模块化引入 2 let http = require ("http"); 3 4 //创建服务器 5 http.createServer(function(requ ...

  3. Spring Boot 面试总结

    1.使用 Spring Boot 前景? 多年来,随着新功能的增加,spring变得越来越复杂.只需访问https://spring.io/projects页面,我们就会看到可以在我们的应用程序中使用 ...

  4. 菜鸡的Java笔记 第三十三 - java 泛型

    泛型 GenericParadigm        1.泛型的产生动机        2.泛型的使用以及通配符        3.泛型方法的使用                JDK1.5 后的三大主 ...

  5. 一文分析 Android现状及发展前景

    Coding这些年,一直低头"搬砖",好像从未仔细审视过Android的发展现状,亦未好好思考Android的发展前景."低头干活,还要抬头看路",写一篇文章简 ...

  6. .NET GC 实时监控 dotnet-gcmon 介绍

    今天介绍一个新的诊断工具 dotnet-gcmon, 也是全局 .NET CLI 工具, 它可以监控到 .NET 程序的 GC, 能获取到的信息也很详细, 另外 maoni 大佬也是其中的开发者之一. ...

  7. cube+FreeRTOS联合开发采坑笔记

    加了看门狗之后不断重启的可能 原因: 任务容量分配不足,在"FreeRTOSConfig.h"的配置中,有个configTOTAL_HEAP_SIZE中将堆大小调到最大.

  8. char数据可以放入int[]中会自动转换

    int[] ary ={'b','c','a','d','e','f'};System.out.println(ary[0]);//98String str = new String(ary, 2, ...

  9. Go语言核心36讲(Go语言实战与应用十五)--学习笔记

    37 | strings包与字符串操作 Go 语言不但拥有可以独立代表 Unicode 字符的类型rune,而且还有可以对字符串值进行 Unicode 字符拆分的for语句. 除此之外,标准库中的un ...

  10. k8s statefulset controller源码分析

    statefulset controller分析 statefulset简介 statefulset是Kubernetes提供的管理有状态应用的对象,而deployment用于管理无状态应用. 有状态 ...