# -*- coding:utf-8 -*-
"""
File Name: shi_pei_qi
Author: wabi
Data: 2020/4/24 16:01
-----------------------
Info:
适配器模式
参考: 精通python设计模式
适配器实现两个不兼容接口之间的兼容
-----------------------
Change Activity:
2020/4/24: create
"""
import logging
logger = logging.getLogger(__file__)
class Synthesizer:
def __init__(self,
name):
self.name = name
def __str__(self):
return 'the {} synthesizer'.format(self.name)
def play(self):
return '一起玩耍,可以吗'
class Human:
def __init__(self,
name):
self.name = name
def __str__(self):
return '姓名:{}'.format(self.name)
def speak(self):
return self.name + ':你好'
class Computer:
def __init__(self,
name):
self.name = name
def __str__(self):
return '{} 电脑'.format(self.name)
def execute(self):
return self.name + ": 执行一个程序"
class Adapter:
"""
适配器
"""
def __init__(self,
obj,
adapter_methods):
self.obj = obj
self.__dict__.update(adapter_methods) # 增加需要配适配的方法
def __str__(self):
return str(self.obj)
def __getattr__(self, item):
"""
访问obj属性
:param item:
:return:
"""
return getattr(self.obj, item)
def main():
objects = [Computer('华为')]
synth = Synthesizer('moog')
human = Human('小明')
objects.append(Adapter(synth, dict(execute=synth.play)))
objects.append(Adapter(human, dict(execute=human.speak)))
for obj in objects:
print('对象={}\nexecute:{}'.format(str(obj), obj.execute()))
print(obj.name)
if __name__ == '__main__':
main()
网友评论