python 适配器模式
来源:互联网 发布:pc安装mac os x10.9 编辑:程序博客网 时间:2024/06/06 02:18
所谓适配器模式是指是一种接口适配技术,它可通过某个类来使用另一个接口与之不兼容的类,运用此模式,两个类的接口都无需改动。
存在一套旧系统,里面包含 Human 和 Synthesizer 类,如下:
class Synthesizer: def __init__(self, name): self.name = name def __str__(self): return 'the {} synthesizer'.format(self.name) def play(self): return 'is playing an electronic song'class Human: def __init__(self, name): self.name = name def __str__(self): return '{} the human'.format(self.name) def speak(self): return 'says hello'
现在新增 Computer 类如下:
class Computer: def __init__(self, name): self.name = name def __str__(self): return 'the {} computer'.format(self.name) def execute(self): return 'executes a program'
并且对于扩展系统来说,所有动作函数均使用 Obj.execute() 来执行。即对于调用者来说,原系统的 Synthesizer.play() 和 Human.speak() 是不存在的,必须像调用 Computer.execute() 一样使用 Synthesizer.execute() 和 Human.execute() 来调用原系统中对象的执行函数。
这就是我们之前提到的场景,无法修改原系统函数,此时新系统就可以采用适配器模式进行设计。
我们可以创建一个 Adapter 类专门用于统一接口,代码如下。
class Adapter: def __init__(self, obj, adapted_methods): self.obj = obj self.__dict__.update(adapted_methods) def __str__(self): return str(self.obj)
简单来说,这里是使用了 Python 的一个特殊语法糖 class.dict 属性,即类的内部字典。这个特殊的属性是一个字典,存放了这个类所包含的所有属性,包括方法。所以这里将传入的类进行处理,将需要被适配器处理的方法添加到内部字典中,生成一个属于这个新适配器对象的方法。
接下来,只需要在调用时,对原有系统的类进行封装,即可实现统一使用 execute() 方法执行动作了。代码如下.
def new_main(): objects = [Computer('Asus')] synth = Synthesizer('moog') objects.append(Adapter(synth, dict(execute=synth.play))) human = Human('Bob') objects.append(Adapter(human, dict(execute=human.speak))) for i in objects: print('{} {}'.format(str(i), i.execute())) print('type is {}'.format(type(i)))
执行结果如下:
the Asus computer executes a programtype is <class '__main__.Computer'>the moog synthesizer is playing an electronic songtype is <class '__main__.Adapter'>Bob the human says hellotype is <class '__main__.Adapter'>
阅读全文
0 0
- 适配器模式(python)
- 适配器模式(python)
- python 适配器模式
- Python适配器模式
- python 适配器模式
- Python设计模式-适配器模式
- python设计模式(适配器模式)
- Python设计模式--适配器模式
- python设计模式之适配器
- Python设计模式——适配器模式
- Python设计模式(二)【适配器模式】
- 设计模式-适配器模式-adapter-python
- 设计模式十(适配器模式,python语言实现)
- 大话设计模式(Python版)--适配器模式
- Python 的结构型设计模式——适配器模式
- Python的结构型设计模式之适配器模式
- 适配器及适配器模式
- 适配器及适配器模式
- JSP中out.write()和out.print()的区别
- JAVA中的反射机制
- Prime Ring Problem
- Android App支付系列(一):微信支付接入详细指南(附官方支付demo)
- docker-compose安装
- python 适配器模式
- SPOJ
- CSS代码重构与优化之路
- 用Action下载文件
- hibernate一级缓存机制(还有二级)
- javascript 常用的编码格式:escape(), encodeURL(), encodeURIComponent()
- fgm实例练习笔记-3.7网页计算器
- js让表单只能输入数字
- 通过隐藏option实现select的联动效果