Skip to content
CodeWithKarthik

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 = []
4
5 def subscribe(self, observer):
6 self.observers.append(observer)
7
8 def unsubscribe(self, observer):
9 self.observers.remove(observer)
10
11 def notify(self, *args, **kwargs):
12 for observer in self.observers:
13 observer.notify(*args, **kwargs)
14
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
4
5 def notify(self):
6 self.send_email()
7
8 def send_email(self):
9 print(f"Sending email to {self.to_address}")
10
11if __name__ == '__main__':
12 email_sender = EmailSender()
13 subscriber1 = EmailObserver("abc@gmail.com")
14 subscriber2 = EmailObserver("efg@gmail.com")
15
16 email_sender.subscribe(subscriber1)
17 email_sender.subscribe(subscriber2)
18 email_sender.notify()
19
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 abc@gmail.com
2Sending email to efg@gmail.com
3Unsubscribing subscriber1
4Sending email to efg@gmail.com
© 2021 by CodeWithKarthik. All rights reserved.
Theme by LekoArts