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适配器模式代码的更多相关文章

  1. 【Python】《大话设计模式》Python版代码实现

    <大话设计模式>Python版代码实现 上一周把<大话设计模式>看完了,对面向对象技术有了新的理解,对于一个在C下写代码比较多.偶尔会用到一些脚本语言写脚本的人来说,很是开阔眼 ...

  2. 《大话设计模式》Python版代码实现

    上一周把<大话设计模式>看完了,对面向对象技术有了新的理解,对于一个在C下写代码比较多.偶尔会用到一些脚本语言写脚本的人来说,很是开阔眼界.<大话设计模式>的代码使用C#写成的 ...

  3. Python一行代码

    1:Python一行代码画出爱心 print]+(y*-)**-(x**(y*<= ,)]),-,-)]) 2:终端路径切换到某文件夹下,键入: python -m SimpleHTTPServ ...

  4. python爬虫代码

    原创python爬虫代码 主要用到urllib2.BeautifulSoup模块 #encoding=utf-8 import re import requests import urllib2 im ...

  5. Python小代码_2_格式化输出

    Python小代码_2_格式化输出 name = input("name:") age = input("age:") job = input("jo ...

  6. Python小代码_1_九九乘法表

    Python小代码_1_九九乘法表 max_num = 9 row = 1 while row <= max_num: col = 1 while col <= row: print(st ...

  7. Python IDLE 代码高亮主题

    Python IDLE 代码高亮主题 使用方法: 打开C盘我的 C:\Documents and Settings\你的用户名.idlerc文件夹 里面会有一个 config-highlight.cf ...

  8. 代码块: 以冒号作为开始,用缩进来划分作用域,这个整体叫做代码块,python的代码块可以提升整体的整齐度,提高开发效率

    # ### 代码块: 以冒号作为开始,用缩进来划分作用域,这个整体叫做代码块 if 5 == 5: print(1) print(2) if True: print(3) print(4) if Fa ...

  9. uiautomatorviewer 优化定位符生成,支持生成Java,Python自动化代码

    项目介绍 二次开发 uiautomatorviewer 优化定位符生成,支持生成Java,Python自动化代码,修复自带工具画面有动态加载时截图失败问题,优化自带工具截图速度 ,实现类似录制脚本功能 ...

随机推荐

  1. pyspark AttributeError: 'NoneType' object has no attribute 'setCallSite'

    pyspark: AttributeError: 'NoneType' object has no attribute 'setCallSite' 我草,是pyspark的bug.解决方法: prin ...

  2. SpringBoot -基础学习笔记 - 01

    SpringBoot个人笔记-szs 一.使用thymeleaf模板引擎来指定所需资源的位置 可以做到当项目名进行更改后,模板引擎也会进行更新相关的路径;如下图展示,会自动添加crud根目录! < ...

  3. 0025SpringMVC的几种响应方式

    本文主要涉及到一下几种响应方式: 1.返回字符串2.返回void3.返回ModelAndView4.转发关键字forward和重定向关键字redirect返回字符串5.ajax调用返回json 具体实 ...

  4. 为什么将项目托管到Apache,浏览器输入http://127.0.0.1会跳转到http://127.0.0.1//dashboard/?

    找到xampp安装的根目录下htdocs文件夹下的index.php文件 <?php if (!empty($_SERVER['HTTPS']) && ('on' == $_SE ...

  5. 火狐谷歌webdriver驱动地址

    ChormeDrive下载 打开百度搜索Chromedriver官网下载,点击进入这个页面,链接为:http://npm.taobao.org/mirrors/chromedriver/2.41/  ...

  6. 08 node.js 的使用

    创建包 目录结构 cmd   cd 到当前目录:  \ 执行 npm init //创建一个包 1 2. 3. 4.包的安装 npm install jquery --save npm install ...

  7. C#在WebApi 中使用Redis 的方法

    首先Startup public void ConfigureServices(IServiceCollection services) { services.AddControllers(); // ...

  8. C# HashCode

    如果两个对象的HashCode相等,可以认为两者相等.类型和值都相等. xx.GetHashCode();

  9. 014_Python3 循环语句

    1.while 循环 #!/usr/bin/env python3   n = 100   sum = 0 counter = 1 while counter <= n:     sum = s ...

  10. html5 打开摄像头

    <video onloadedmetadata="" id="inputVideo" style="width: 1080px;height: ...