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

yipeiwu_com6年前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设计】。

相关文章

Python3 合并二叉树的实现

Python3 合并二叉树的实现

题目要求:给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点...

VSCode中自动为Python文件添加头部注释

VSCode中自动为Python文件添加头部注释

在实际编写Python文件时,往往需要为文件添加相关说明,例如文件名称、文件作用、创建时间、作者信息、版本号等等。这些信息往往是固定模板的,因此希望有一种方式可以自动的为我们添加上这些信...

Python3安装psycopy2以及遇到问题解决方法

Python3安装psycopy2以及遇到问题解决方法

事先在网上搜索了一大圈,头都大了,看到那么多文章写道在python里安装psycopg2的各种坑和各种麻烦,各种不成功。搜索了一下午,索性外出放松。晚饭后,又继续上psycopg2官网(...

Pytorch之卷积层的使用详解

1.简介(torch.nn下的) 卷积层主要使用的有3类,用于处理不同维度的数据 参数 Parameters: in_channels(int) – 输入信号的通道 out_channe...

Python制作微信好友背景墙教程(附完整代码)

Python制作微信好友背景墙教程(附完整代码)

引言 前段时间,微信朋友圈开始出现了一种晒照片新形式,微信好友墙,即在一张大图片中展示出自己的所有微信好友的头像。 效果如下图,出于隐私考虑,这里作了模糊处理。 是不是很炫,而且这还...