forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpublish_subscribe.py
77 lines (58 loc) · 1.59 KB
/
publish_subscribe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
'''
Reference: http://www.slideshare.net/ishraqabd/publish-subscribe-model-overview-13368808
Author: https://github.com/HanWenfang
'''
class Provider:
def __init__(self):
self.msgQueue = []
self.subscribers = {}
def notify(self, msg):
self.msgQueue.append(msg)
def subscribe(self,msg, subscriber):
if not msg in self.subscribers:
self.subscribers[msg] = []
self.subscribers[msg].append(subscriber) #unfair
else:
self.subscribers[msg].append(subscriber)
def unSubscribe(self,msg, subscriber):
self.subscribers[msg].remove(subscriber)
def update(self):
for msg in self.msgQueue:
if msg in self.subscribers:
for sub in self.subscribers[msg]:
sub.run(msg)
self.msgQueue = []
class Publisher:
def __init__(self, msgCenter):
self.provider = msgCenter
def publish(self, msg):
self.provider.notify(msg)
class Subscriber:
def __init__(self,name,msgCenter):
self.name = name
self.provider = msgCenter
def subscribe(self, msg):
self.provider.subscribe(msg, self)
def run(self, msg):
print "%s got %s"%(self.name, msg)
def main():
messageCenter = Provider()
fftv = Publisher(messageCenter)
jim = Subscriber("jim", messageCenter)
jim.subscribe("cartoon")
jack = Subscriber("jack", messageCenter)
jack.subscribe("music")
gee = Subscriber("gee", messageCenter)
gee.subscribe("movie")
fftv.publish("cartoon")
fftv.publish("music")
fftv.publish("ads")
fftv.publish("movie")
fftv.publish("cartoon")
fftv.publish("cartoon")
fftv.publish("movie")
fftv.publish("blank")
messageCenter.update()
if __name__ == "__main__":
main()