设计模式--观察者模式
生活随笔
收集整理的這篇文章主要介紹了
设计模式--观察者模式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近看設計模式,其中談及到觀察者模式.
可以理解為被觀察者對外提供注冊機制,觀察者可以通過插入和移除實現訂閱和取消訂閱消息的功能,無論觀察者有沒有注冊, 都不會影響被觀察者發布消息.
而這在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, ):passself._hooks = []def register_hook(self, hook):# 這里不做優先級判斷,直接在頭部插入HOOKself._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()?
總結
以上是生活随笔為你收集整理的设计模式--观察者模式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Opencv——灰度变换、直方图均衡化
- 下一篇: 常见的设计模式--单例模式