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)

转载于:https://www.cnblogs.com/huazi/archive/2012/07/23/2604282.html

你可能感兴趣的:(python实现简单消息总线)