Python适配器模式代码实现解析
Python适配器模式,代码,思考等
#-*-coding:utf-8-*-
#author:baoshan
classComputer:
def__init__(self,name):
self.name=name
def__str__(self):
return'the{}computer'.format(self.name)
defexecute(self):
return'executesaprogram'
classSynthesizer:
def__init__(self,name):
self.name=name
def__str__(self):
return'the{}synthesizer'.format(self.name)
defplay(self):
return'isplayinganelectronicsong'
classHuman:
def__init__(self,name):
self.name=name
def__str__(self):
return'{}thehuman'.format(self.name)
defspeak(self):
return'sayshello'
classAdapter:
def__init__(self,obj,adapted_methods):
self.obj=obj
self.__dict__.update(adapted_methods)
def__str__(self):
returnstr(self.obj)
defmain():
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)))
foriinobjects:
print('{}{}'.format(str(i),i.execute()))
if__name__=='__main__':
main()
代码输出:
theAsuscomputerexecutesaprogram themoogsynthesizerisplayinganelectronicsong Bobthehumansayshello
我们设法使得Human和Synthesizer类与客户端所期望的接口兼容,且无需改变它们的源代码。这太棒了!
这里有一个为你准备的挑战性练习,当前的实现有一个问题,当所有类都有一个属性name时,以下代码会运行失败。
foriinobjects:
print('{}'.format(i.name))
首先想想这段代码为什么会失败?虽然从编码的角度来看这是有意义的,但对于客户端代码来说毫无意义,客户端不应该关心“适配了什么”和“什么没有被适配”这类细节。我们只是想提供一个统一的接口。该如何做才能让这段代码生效?
思考一下如何将未适配部分委托给包含在适配器类中的对象。
答案如下:
将适配器类更改如下,增加一行代码
classAdapter: def__init__(self,obj,adapted_methods): self.obj=obj self.__dict__.update(adapted_methods) self.name=obj.name def__str__(self): returnstr(self.obj)
然后在main函数中获取对应的name,如下
defmain():
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)))
foriinobjects:
print('{}{}'.format(str(i),i.execute()))
print('{}'.format(i.name))
if__name__=='__main__':
main()
输出结果如下:
theAsuscomputerexecutesaprogram Asus themoogsynthesizerisplayinganelectronicsong moog Bobthehumansayshello Bob
参考自:《精通Python设计模式》
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。