华子的代码空间

逆水行舟,不进则退。 关注系统编程、网络编程、并发、分布式。

python实现简单消息总线

一句话概括:其实核心就是用了回调机制。

 1 class PyBus (object):
 2 
 3     def __init__(self,):
 4         self.clear()
 5         
 6     def clear(self):
 7         self.subscriptions = {}
 8     
 9     def subscribe(self, subject, owner, func):
10         if not self.subscriptions.has_key(owner):
11             self.subscriptions[owner] = {}
12         self.subscriptions[owner][subject] = func
13         
14     def has_subscription(self, owner, subject):
15         return self.subscriptions.has_key(owner) and self.subscriptions[owner].has_key(subject)
16         
17     def publish(self, subject, *args, **kwargs):
18         for owner in self.subscriptions.keys():
19             if self.has_subscription(owner, subject):
20                 self.subscriptions[owner][subject](*args, **kwargs)

posted on 2012-07-23 01:27  华子的代码空间  阅读(1333)  评论(0编辑  收藏  举报

导航