Skip to content

Observer Pattern

1 min read

Last week we learned about Strategy pattern, today we are going to see about Observer pattern.

The Observer pattern is a behavioral design pattern in which an object can have multiple dependents(can be called observers) which will get notified when the state of the object changes.

Some of the terms we need to know are

  • Observer - Dependents which should get notified
  • Observable - Object which will notify its observers

A real-world example of this pattern is magazine company subscription service. Let's say we are subscribing to a magazine. Here the magazine company is the object they will have the list of dependents (people who are subscribed to their magazine). Whenever a new magazine is published, it will be sent to all the subscribers.

Some of the technical examples of Observer pattern are

  • Model View Controller Pattern (Here View represents Observer and Model represents Observable)
  • LiveData in Android
  • In Social media platforms like Facebook/Twitter, a person can post or update his status and their followers will get a notification.

Lets see how we can implement this pattern in Python

1class Subject(object):
2 def __init__(self):
3 self.observers = []
5 def subscribe(self, observer):
6 self.observers.append(observer)
8 def unsubscribe(self, observer):
9 self.observers.remove(observer)
11 def notify(self, *args, **kwargs):
12 for observer in self.observers:
13 observer.notify(*args, **kwargs)
15class EmailSender(Subject):
16 pass

In the above code, we have a Subject which has methods for subscribing/unsubscribing observers. Also, we have a method called notify, whenever the user wants to send emails to his subscribers he can call this method.

Note that we have written the common code for observer pattern in a separate class called Subject . This is for reusability and for cleaner code.

1class EmailObserver(object):
2 def __init__(self, email):
3 self.to_address = email
5 def notify(self):
6 self.send_email()
8 def send_email(self):
9 print(f"Sending email to {self.to_address}")
11if __name__ == '__main__':
12 email_sender = EmailSender()
13 subscriber1 = EmailObserver("")
14 subscriber2 = EmailObserver("")
16 email_sender.subscribe(subscriber1)
17 email_sender.subscribe(subscriber2)
18 email_sender.notify()
20 print("Unsubscribing subscriber1")
21 email_sender.unsubscribe(subscriber1)
22 email_sender.notify()

In the above code we have defined Observer and subscribed it to EmailSender

The above code will output the following

1Sending email to
2Sending email to
3Unsubscribing subscriber1
4Sending email to
© 2021 by CodeWithKarthik. All rights reserved.
Theme by LekoArts