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

作者:宝山方圆 时间:2023-04-15 12:58:14 

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设计模式》

来源:https://www.cnblogs.com/zhzhang/p/11287648.html

标签:python,适配器,模式,代码
0
投稿

猜你喜欢

  • MongoDB orm框架的注意事项及简单使用

    2024-01-17 07:04:16
  • sql语句查询重复的数据(最新推荐)

    2024-01-13 08:01:23
  • 基于python使用OpenCV进行物体轮廓排序

    2022-06-27 23:25:01
  • Django 登陆验证码和中间件的实现

    2021-08-12 10:26:18
  • asp自动采集程序

    2009-02-04 10:11:00
  • GOLang IO接口与工具使用方法讲解

    2024-04-30 10:05:15
  • js操作两个json数组合并、去重,以及删除某一项元素

    2024-04-18 10:58:23
  • MySQL中 and or 查询的优先级分析

    2024-01-12 13:53:50
  • python实现串口通信的示例代码

    2023-08-04 03:44:24
  • SQLServer用t-sql命令批量删除数据库中指定表(游标循环删除)

    2024-01-16 15:45:54
  • python文件比较示例分享

    2023-03-17 21:10:23
  • MySQL INT类型全解析

    2024-01-27 23:17:01
  • python各种excel写入方式的速度对比

    2021-04-23 22:30:15
  • python使用Windows的wmic命令监控文件运行状况,如有异常发送邮件报警

    2022-01-13 09:48:25
  • 慎用UL列表

    2009-03-25 20:21:00
  • Mysql彻底解决中文乱码问题的方案(Illegal mix of collations for operation)

    2024-01-26 16:33:51
  • Python基于sklearn库的分类算法简单应用示例

    2022-08-21 19:44:42
  • asp如何在第10000名来访者访问时显示中奖页面?

    2010-06-18 19:45:00
  • python utc datetime转换为时间戳的方法

    2021-11-18 07:11:44
  • numpy中的delete删除数组整行和整列的实例

    2022-11-24 22:09:01
  • asp之家 网络编程 m.aspxhome.com