Python适配器模式代码
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】《大话设计模式》Python版代码实现
<大话设计模式>Python版代码实现 上一周把<大话设计模式>看完了,对面向对象技术有了新的理解,对于一个在C下写代码比较多.偶尔会用到一些脚本语言写脚本的人来说,很是开阔眼 ...
- 《大话设计模式》Python版代码实现
上一周把<大话设计模式>看完了,对面向对象技术有了新的理解,对于一个在C下写代码比较多.偶尔会用到一些脚本语言写脚本的人来说,很是开阔眼界.<大话设计模式>的代码使用C#写成的 ...
- Python一行代码
1:Python一行代码画出爱心 print]+(y*-)**-(x**(y*<= ,)]),-,-)]) 2:终端路径切换到某文件夹下,键入: python -m SimpleHTTPServ ...
- python爬虫代码
原创python爬虫代码 主要用到urllib2.BeautifulSoup模块 #encoding=utf-8 import re import requests import urllib2 im ...
- Python小代码_2_格式化输出
Python小代码_2_格式化输出 name = input("name:") age = input("age:") job = input("jo ...
- Python小代码_1_九九乘法表
Python小代码_1_九九乘法表 max_num = 9 row = 1 while row <= max_num: col = 1 while col <= row: print(st ...
- Python IDLE 代码高亮主题
Python IDLE 代码高亮主题 使用方法: 打开C盘我的 C:\Documents and Settings\你的用户名.idlerc文件夹 里面会有一个 config-highlight.cf ...
- 代码块: 以冒号作为开始,用缩进来划分作用域,这个整体叫做代码块,python的代码块可以提升整体的整齐度,提高开发效率
# ### 代码块: 以冒号作为开始,用缩进来划分作用域,这个整体叫做代码块 if 5 == 5: print(1) print(2) if True: print(3) print(4) if Fa ...
- uiautomatorviewer 优化定位符生成,支持生成Java,Python自动化代码
项目介绍 二次开发 uiautomatorviewer 优化定位符生成,支持生成Java,Python自动化代码,修复自带工具画面有动态加载时截图失败问题,优化自带工具截图速度 ,实现类似录制脚本功能 ...
随机推荐
- 洛谷 P1280 尼克的任务题解
题目链接:https://www.luogu.org/problem/P1280 题目描述 尼克每天上班之前都连接上英特网,接收他的上司发来的邮件,这些邮件包含了尼克主管的部门当天要完成的全部任务,每 ...
- 最小生成树:Tree
参考资料:https://blog.csdn.net/sunshinezff/article/details/48749453 Description 给你一个无向带权连通图,每条边是黑色或白色.让你 ...
- 忘记 MySQL 的 root 帐号密码该怎么办
如果你忘了 MySQL 的 root 帐号密码,别担心,使用下面步骤就可以重设一个新密码: 首先停止 MySQL 服务 “/etc/init.d/mysql stop” 启动 MySQL 服务并屏蔽用 ...
- .net序列化 - Newtonsoft(Json.Net)简单应用
Newtonsoft.Json,一款.NET中开源的Json序列化和反序列化类库. Json.Net是一个读写Json效率比较高的.Net框架.Json.Net 使得在.Net环境下使用Json更加简 ...
- 微信小程序引入Vant组件库
前期准备 Vant Weapp组件库:https://youzan.github.io/vant-weapp/#/intro 1.先在微信开发者工具中打开项目的终端: 然后初始化一个package.j ...
- Tensorflow细节-P80-深度神经网络
1.本节多为复习内容,从以下图片可见一般: 2.学会使用 from numpy.random import RandomState 然后 rdm = RandomState(1) dataset_si ...
- Oracle 重新编译存储过程/函数等
第一种 如果你使用 PL/SQL Developer工具 左侧工具栏中选择“存储过程”->选择已经失效的procedure->右键->选择重新编译 即可完成 第二 ...
- vue组件传值的三种方式,文字版解释
父传子: 当子组件子父组件中当标签使用的时候,给子组件添加一个自定义属性,值为需要传递的值(如: <Child v-bind:parentToChild="parentMsg" ...
- codevs:2849 素数判定 3:输入一个正整数x(3<=x<=100000),判断x是否是质数,如果是质数则输出信息“prime”,否则输出“composite”。
#include<iostream>#include<cstdio>#include<cmath>using namespace std;int a[2];int ...
- 洛谷 P1855 榨取kkksc03 题解
P1855 榨取kkksc03 题目描述 洛谷2的团队功能是其他任何oj和工具难以达到的.借助洛谷强大的服务器资源,任何学校都可以在洛谷上零成本的搭建oj并高效率的完成训练计划. 为什么说是搭建oj呢 ...