使用python实现观察者思想
2014-02-28 10:28
288 查看
#coding=utf-8 class Observer(object): def __init__(self): self.handlersDic = {} def fireEvent(self, eventKey, **kw): """ 触发 """ eList = self.handlersDic.get(eventKey,[]) for handler in eList: handler(**kw) def un(self,eventKey, handler): """ 在事件字典里删除相关方法 """ eList = self.handlersDic.get(eventKey,[]) for i in range(len(eList)-1, -1, -1): if eList[i] == handler: del eList[i] def on(self,eventKey, handler): """ 关联 """ eList = self.handlersDic.get(eventKey,[]) if not eList: self.handlersDic[eventKey] = eList eList.append(handler) if __name__ == '__main__': import time def eatFood(t): print "i am eat food at %s!" %t o = Observer() o.on("eatingFood", eatFood) def singing(): print "i am singing!" t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())) o.fireEvent("eatingFood", t=t) singing()
相关文章推荐
- 使用python实现递归版汉诺塔示例(汉诺塔递归算法)
- 使用SWIG实现C++导出python接口的配置
- Python 中实现装饰器时使用 @functools.wraps 的理由
- ubuntu安装rabbitmq和python的使用实现
- 按钮实现Python--绘图工具matplotlib的使用
- python实现SMTP发邮件(不需要注册邮箱使用邮箱的SMTP服务)
- 二种python发送邮件实例讲解(python发邮件附件可以使用email模块实现)
- 如何使用Python和Nose实现自动化测试?
- python3 使用 fabric3 模块实现密钥登录远程主机
- python3使用tkinter实现ui界面简单实例
- 使用Python实现质因式分解算法
- Python(17)python使用tkinter实现一个简单的CSGO幸运转盘抽奖游戏
- Python下使用tarfile模块来实现文件归档压缩与解压
- python cgi ajax - 使用CGIHTTPServer实现一个ajax程序
- Python使用Matplotlib和Imagemagick实现感知器算法可视化与GIF导出
- 使用python实现Strassen矩阵乘法算法
- 使用python3的base64编解码实现字符串的简易加密解密
- 使用Python实现一个简单的项目监控
- Python使用win32com实现的模拟浏览器功能示例
- 设计模式-观察者模式,以及如何使用观察者来为app实现即时通讯功能