适配器模式适应在这种场景:客户端需要调用类的方法,但这个类没有这个方法,可以把这个类放到适配器类中加工一下,让适配器具有这有这个方法,这个适配器方法来做类方法的封装。比如,客户端想调用类A的watch_tv方法,但类A中只有turn_on_power(),turn_on_tv()方法。因此可以把类A放入适配器类中,让适配器具有watch_tv方法,并且这个watch_tv方法是turn_on_power()和turn_on_tv()方法的封装。
代码具体实现:
客户端类: Client--方法 show_time
被调用的类: Electronic_clock, 方法show_accurate_time
Mechanical_clock, 方法every_wind(每天上发条), periodic_calibration_time(定期校准时间), show_time
适配器类:Adapter 方法 show_accurate_time
实现了客户端类Client,Client中具有show_time方法,这个方法调用的是Electronic_clock的show_time方法,但Mechanical_clock类中没有show_accurate_time方法,它只有every_wind,periodic_calibration_time, show_time。因此,如果想被客户端调用的话就需要适配器进行加工。代码如下
import datetime
class Electronic_clock(object):
def show_accurate_time(self):
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 现在
print('from electronic clock: now time is %s' % now_time)
class Mechanical_clock(object):
def every_wind(self):
print('每天上发条')
def periodic_calibration_time(self):
print('定期校准时间')
def show_time(self):
now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 现在
print('from mechanical clock: now time is %s' % now_time)
class Adapter(object):
def __init__(self, me_clock):
self.clock = me_clock
def show_accurate_time(self):
self.clock.every_wind()
self.clock.periodic_calibration_time()
self.clock.show_time()
class Client(object):
def __init__(self, clock):
self.clock = clock
def show_time(self):
self.clock.show_accurate_time()
if __name__ == '__main__':
m_clock = Mechanical_clock()
e_clock = Electronic_clock()
client = Client(e_clock)
client.show_time()
print('*'*40)
adapter = Adapter(m_clock)
client.clock = adapter
client.show_time()
结果如下
from electronic clock: now time is 2018-07-04 09:00:13
****************************************
每天上发条
定期校准时间
from mechanical clock: now time is 2018-07-04 09:00:13