Skip to content

Instantly share code, notes, and snippets.

@ssbozy
Created August 27, 2022 04:10
Show Gist options
  • Save ssbozy/09cfd44bab6b15391eb9e883a01810f0 to your computer and use it in GitHub Desktop.
Save ssbozy/09cfd44bab6b15391eb9e883a01810f0 to your computer and use it in GitHub Desktop.
Basic example of observer pattern in python using Publisher and Subscriber code
class Subscriber:
def __init__(self, name):
self._name = name
def update(self, message):
print(f"{self._name} received the message {message}")
class Publisher:
def __init__(self):
self._subscribers = set()
def register(self, candidate):
self._subscribers.add(candidate)
def unregister(self, candidate):
self._subscribers.discard(candidate)
def dispatch(self, message):
for eachsubscriber in self._subscribers:
eachsubscriber.update(message)
a = Subscriber("alice")
b = Subscriber("bob")
c = Subscriber("cathy")
d = Subscriber("dom")
pub = Publisher()
pub.register(a)
pub.register(b)
pub.register(c)
pub.register(d)
pub.dispatch("Hello World")
pub.unregister(d)
pub.unregister(b)
pub.dispatch("New World")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment