Python适配器模式代码实现解析


Posted in Python onAugust 02, 2019

Python适配器模式,代码,思考等

# -*- coding: utf-8 -*-
# author:baoshan
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'
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'
class Adapter:
  def __init__(self, obj, adapted_methods):
    self.obj = obj
    self.__dict__.update(adapted_methods)
def __str__(self):
    return str(self.obj)
def 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()))
if __name__ == '__main__':
  main()

代码输出:

the Asus computer executes a program
the moog synthesizer is playing an electronic song
Bob the human says hello

------------------------------------------------------------------------------------------

我们设法使得Human和Synthesizer类与客户端所期望的接口兼容,且无需改变它们的源代码。这太棒了!

这里有一个为你准备的挑战性练习,当前的实现有一个问题,当所有类都有一个属性name时,以下代码会运行失败。

for i in objects:
    print('{}'.format(i.name))

首先想想这段代码为什么会失败?虽然从编码的角度来看这是有意义的,但对于客户端代码来说毫无意义,客户端不应该关心“适配了什么”和“什么没有被适配”这类细节。我们只是想提供一个统一的接口。该如何做才能让这段代码生效?

思考一下如何将未适配部分委托给包含在适配器类中的对象。

答案如下:

将适配器类更改如下,增加一行代码

class Adapter:
  def __init__(self, obj, adapted_methods):
    self.obj = obj
    self.__dict__.update(adapted_methods)
    self.name = obj.name
  def __str__(self):
    return str(self.obj)

然后在main函数中获取对应的name,如下

def 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('{}'.format(i.name))
if __name__ == '__main__':
  main()

输出结果如下:

the Asus computer executes a program
Asus
the moog synthesizer is playing an electronic song
moog
Bob the human says hello
Bob

参考自:《精通Python设计模式》

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python多线程、异步+多进程爬虫实现代码
Feb 17 Python
Python队列的定义与使用方法示例
Jun 24 Python
基于Python实现的ID3决策树功能示例
Jan 02 Python
python3.6+opencv3.4实现鼠标交互查看图片像素
Feb 26 Python
对python-3-print重定向输出的几种方法总结
May 11 Python
Python操作word常见方法示例【win32com与docx模块】
Jul 17 Python
对python的unittest架构公共参数token提取方法详解
Dec 17 Python
Python作用域与名字空间原理详解
Mar 21 Python
python数据库操作mysql:pymysql、sqlalchemy常见用法详解
Mar 30 Python
python 负数取模运算实例
Jun 03 Python
什么是python的必选参数
Jun 21 Python
python实现定时发送邮件到指定邮箱
Dec 23 Python
Python3网络爬虫开发实战之极验滑动验证码的识别
Aug 02 #Python
pandas中DataFrame修改index、columns名的方法示例
Aug 02 #Python
pandas DataFrame的修改方法(值、列、索引)
Aug 02 #Python
Flask框架钩子函数功能与用法分析
Aug 02 #Python
pandas DataFrame行或列的删除方法的实现示例
Aug 02 #Python
Python基于BeautifulSoup和requests实现的爬虫功能示例
Aug 02 #Python
详解pandas DataFrame的查询方法(loc,iloc,at,iat,ix的用法和区别)
Aug 02 #Python
You might like
Discuz 5.0 中读取纯真IP数据库函数分析
2007/03/16 PHP
不重新编译PHP为php增加openssl模块的方法
2011/06/14 PHP
laravel框架数据库操作、查询构建器、Eloquent ORM操作实例分析
2019/12/20 PHP
javascript showModalDialog 多层模态窗口实现页面提交及刷新的代码
2009/11/28 Javascript
jQuery插件-jRating评分插件源码分析及使用方法
2012/12/28 Javascript
appendChild() 或 insertBefore()使用与区别介绍
2013/10/11 Javascript
jQuery实现鼠标划过修改样式的方法
2015/04/14 Javascript
javascript结合Flexbox简单实现滑动拼图游戏
2016/02/18 Javascript
浅谈JavaScript中小数和大整数的精度丢失
2016/05/31 Javascript
jQuery实现checkbox即点即改批量删除及中间遇到的坑
2017/11/11 jQuery
JS判断两个数组或对象是否相同的方法示例
2019/02/28 Javascript
用js限制网页只在微信浏览器中打开(或者只能手机端访问)
2020/12/24 Javascript
JavaScript运动原理基础知识详解
2020/04/02 Javascript
Python 正则表达式入门(初级篇)
2016/12/07 Python
python使用threading获取线程函数返回值的实现方法
2017/11/15 Python
Python 做曲线拟合和求积分的方法
2018/12/29 Python
python数据类型之间怎么转换技巧分享
2019/08/20 Python
详解python中各种文件打开模式
2020/01/19 Python
python分布式爬虫中消息队列知识点详解
2020/11/26 Python
Spartoo芬兰:欧洲最大的网上鞋店
2016/08/28 全球购物
一套C++笔试题面试题
2012/06/06 面试题
我们在web应用开发过程中经常遇到输出某种编码的字符,如iso8859-1等,如何输出一个某种编码的字符串?
2014/03/30 面试题
机械设计及其自动化专业推荐信
2013/10/31 职场文书
2014年端午节活动方案
2014/03/11 职场文书
中国梦团日活动总结
2014/07/07 职场文书
工资收入证明
2014/10/07 职场文书
2014年办公室个人工作总结
2014/11/12 职场文书
第28个世界无烟日活动总结
2015/02/10 职场文书
新员工试用期自我评价
2015/03/10 职场文书
个人总结与自我评价2015
2015/03/11 职场文书
公司年夜饭通知
2015/04/25 职场文书
三十年同学聚会致辞
2015/07/28 职场文书
python实现网络五子棋
2021/04/11 Python
Go语言使用select{}阻塞main函数介绍
2021/04/25 Golang
mysql中int(3)和int(10)的数值范围是否相同
2021/10/16 MySQL
MySQL主从切换的超详细步骤
2022/06/28 MySQL