Skip to content

Commit

Permalink
publish_subscribe pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
indieyourself committed Dec 20, 2013
1 parent 1db5bff commit 836ddd0
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 1 deletion.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,5 @@ Current Patterns:
* template
* command
* memento
* visitor
* visitor
* publish_subscribe
74 changes: 74 additions & 0 deletions publish_subscribe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#!/usr/bin/env python

'''http://www.slideshare.net/ishraqabd/publish-subscribe-model-overview-13368808'''

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()

0 comments on commit 836ddd0

Please sign in to comment.