当前位置 博文首页 > DL_fan的博客:设计模式--观察者模式

    DL_fan的博客:设计模式--观察者模式

    作者:[db:作者] 时间:2021-06-25 09:23

    最近看设计模式,其中谈及到观察者模式.

    可以理解为被观察者对外提供注册机制,观察者可以通过插入和移除实现订阅和取消订阅消息的功能,无论观察者有没有注册, 都不会影响被观察者发布消息.

    而这在mmdetection中体现的很好.

    举个例子来观察每天我的生活:

    其中register_hook用来注册HOOK来判断是否要观察我的每天生活.

    import sys
    class HOOK:
    
        def before_getup(self, runner):
            print('{}:赖床30分钟'.format(sys._getframe().f_code.co_name))
            print('==runner:', runner)
        def after_getup(self, runner):
            print('{}:刷牙洗脸'.format(sys._getframe().f_code.co_name))
            print('==runner:', runner)
        def before_lunch(self, runner):
            print('{}:吃午饭之前上厕所'.format(sys._getframe().f_code.co_name))
            print('==runner:', runner)
        def after_lunch(self, runner):
            print('{}:吃完午饭午休30分钟'.format(sys._getframe().f_code.co_name))
            print('==runner:', runner)
        def before_dinner(self, runner):
            print('{}: 摸鱼30分钟'.format(sys._getframe().f_code.co_name))
            print('==runner:', runner)
        def after_dinner(self, runner):
            print('{}: 回家睡觉'.format(sys._getframe().f_code.co_name))
            print('==runner:', runner)
    
        def after_finish_work(self, runner, are_you_busy=False):
            if are_you_busy:
                print('{}:今天事贼多,还是加班吧'.format(sys._getframe().f_code.co_name))
            else:
                print('{}:今天没啥事,看部电影'.format(sys._getframe().f_code.co_name))
            print('==runner:', runner)
    
    class Runner(object):
        def __init__(self, ):
            pass
            self._hooks = []
    
        def register_hook(self, hook):
            # 这里不做优先级判断,直接在头部插入HOOK
            self._hooks.insert(0, hook)
    
        def call_hook(self, hook_name):
            for hook in self._hooks:
                getattr(hook, hook_name)(self)
    
        def run(self):
            print('开始启动我的一天')
            self.call_hook('before_getup')
            self.call_hook('after_getup')
            self.call_hook('before_lunch')
            self.call_hook('after_lunch')
            self.call_hook('before_dinner')
            self.call_hook('after_dinner')
            self.call_hook('after_finish_work')
            print('睡觉算求')
    
    runner = Runner()
    hook = HOOK()
    runner.register_hook(hook)
    runner.run()
    

    ?

    下一篇:没有了