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自动化代码,修复自带工具画面有动态加载时截图失败问题,优化自带工具截图速度 ,实现类似录制脚本功能 ...
随机推荐
- 《你说对就队》第八次团队作业:Alpha冲刺 第二天
<你说对就队>第八次团队作业:Alpha冲刺 项目 内容 这个作业属于哪个课程 [教师博客主页链接] 这个作业的要求在哪里 [作业链接地址] 团队名称 <你说对就队> 作业学习 ...
- 棋盘覆盖 状压DP+矩阵快速幂
题意:有一个m 行n 列的矩形方格棋盘,1 < = m< = 5,1=< n< =10^9,用1*2 的骨牌(可横放或竖放)完全覆盖,骨牌不能重叠,有多少种不同的覆盖的方法.你 ...
- C# 异步的简单用法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- PostgreSQL物理坏块和文件损坏案例分享
作者简介 王睿操,平安好医数据库架构岗,多年postgresql数据库运维开发工作.曾就职于中国民航信息,迪卡侬.对其他数据库产品也有一定的涉猎. 背景 笔者最近发现很多朋友经常遇到PostgreSQ ...
- 017_Python3 数据结构
本章节我们主要结合前面所学的知识点来介绍Python数据结构. ***************************** 1.列表 Python中列表是可变的,这是它区别于字符串和元组的最重 ...
- Problem 6 二分
$des$有 $n$ 个物品,第 $i$ 个物品有两个属性 $k_i, b_i$ ,表示它在时刻 $x$ 的价值为 $k_i \times x + b_i$ .当前处于时刻 $0$ ,你可以选择不超过 ...
- noi.ac #39 MST
MST 模板题 #include <iostream> #include <cstdio> #include <algorithm> #include <cm ...
- codecs 1264 芳香数
1264 芳香数 题目描述 Description This question involves calculating the value of aromatic numbers which are ...
- 深入剖析mmu地址转化
mmu(内存管理单元),是arm区别于单片机的标志之一,虚拟地址转化分为3种,常见的如下2种. 段式转化如下,由表像中的基地址加偏移地址,(细页转化跟段式转化类似,多了一个2级页表,把虚拟地址0-20 ...
- (28)打鸡儿教你Vue.js
单件商品金额计算和单选全选功能 new Vue({ el: '#app', data: { totalMoney: 0, productList: [] }, filters: { formatMon ...