python 设计模式(九) 适配器模式(adapter pattern)

适配器模式适应在这种场景:客户端需要调用类的方法,但这个类没有这个方法,可以把这个类放到适配器类中加工一下,让适配器具有这有这个方法,这个适配器方法来做类方法的封装。比如,客户端想调用类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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值