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

yipeiwu_com5年前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生成随机验证码的方法有很多种,今天小编给大家分享两种方法,大家可以灵活运用这两种方法,设计出适合自己的验证码方法。 方法一: 利用range方法,对于range方法不清楚...

pybind11在Windows下的使用教程

pybind11在Windows下的使用教程

Pybind11算是目前最方便的Python调用C++的工具了, 介绍一下在vs2019上写Python的扩展的HelloWorld 1. 去下载pybind11  ...

Python安装第三方库及常见问题处理方法汇总

源码安装 Python第三方库几乎都可以在github或者 pypi上找到源码。源码包格式大概有zip 、 tar.zip、 tar.bz2。解压这些包,进入解压好的文件夹,通常会有一个...

使用Python神器对付12306变态验证码

使用Python神器对付12306变态验证码

临近春节,【听图阁-专注于Python设计】小编带领大家用Python抢火车票! 首先我们需要splinter 安装: pip install splinter -i http://py...

基于python(urlparse)模板的使用方法总结

一、简介 urlparse模块用户将url解析为6个组件,并以元组形式返回,返回的6个部分,分别是:scheme(协议)、netloc(网络位置)、path(路径)、params(路径段...