Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple implementation of Pub/Sub Pattern in language python
#!/usr/bin/env python
from collections import defaultdict
class Intermedia:
channels = defaultdict(dict)
@classmethod
def broadcast(cls, channel, msg):
'''broadcast a message to specific subscribers'''
for name, callback in cls.channels[channel].items():
callback({
'channel': channel,
'msg': msg,
'name': name
})
@classmethod
def register(cls, channel, subscriber):
'''register a subscriber into specific channel'''
cls.channels[channel][subscriber.name] = subscriber.callback
@classmethod
def unregister(cls, channel, subscriber):
'''unregister a subscriber from specific channel'''
del cls.channels[channel][subscriber.name]
class Publisher:
@classmethod
def publish(self, channel, msg):
'''publish a message to specific channel'''
Intermedia.broadcast(channel, msg)
class Subscriber:
def __init__(self, name, callback=None):
self.name = name
self.callback = callback if callable(callback) else self.callback
def callback(self, msg):
'''default event handler for current subscriber'''
print('Subscriber "{0[name]}" receive message "{0[msg]}" from channel "{0[channel]}"'.format(msg))
def subscribe(self, channel):
'''subscribe specific channel from publisher'''
Intermedia.register(channel, self)
def unsubscribe(self, channel):
'''unsubscribe specific channel from publisher'''
Intermedia.unregister(channel, self)
if __name__ == '__main__':
# initialize objects
Subscribers = {
'a': Subscriber('a'),
'b': Subscriber('b'),
'c': Subscriber('c', lambda msg: print('"{0[name]}": "{0[msg]}" @ {0[channel]}'.format(msg)))
}
# begin pub/sub procedure
Subscribers['a'].subscribe('cat')
Subscribers['b'].subscribe('dog')
Subscribers['c'].subscribe('cat')
Subscribers['c'].subscribe('dog')
Publisher.publish('cat', 'Cats are so lovely!')
Publisher.publish('dog', 'Dogs are cute, but cats are better!')
Subscribers['b'].unsubscribe('dog')
Publisher.publish('dog', 'Correction: dogs & cats are both very lovely!')
@queensferryme

This comment has been minimized.

Copy link
Owner Author

queensferryme commented Feb 7, 2019

Environment: Python 3.6.7
Expected Output:

Subscriber "a" receive message "Cats are so lovely!" from channel "cat"
"c": "Cats are so lovely!" @ cat
Subscriber "b" receive message "Dogs are cute, but cats are better!" from channel "dog"
"c": "Dogs are cute, but cats are better!" @ dog
"c": "Correction: dogs & cats are both very lovely!" @ dog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.