DEV Community

Karthik Raja
Karthik Raja

Posted on • Originally published at

Observer Pattern

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

class Subject(object):
    def __init__(self):
        self.observers = []

    def subscribe(self, observer):

    def unsubscribe(self, observer):

    def notify(self, *args, **kwargs):
        for observer in self.observers:
            observer.notify(*args, **kwargs)

class EmailSender(Subject):
Enter fullscreen mode Exit fullscreen mode

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.

class EmailObserver(object):
    def __init__(self, email):
        self.to_address = email

    def notify(self):

    def send_email(self):
        print(f"Sending email to {self.to_address}")

if __name__ == '__main__':
    email_sender = EmailSender()
    subscriber1 = EmailObserver("")
    subscriber2 = EmailObserver("")


    print("Unsubscribing subscriber1")
Enter fullscreen mode Exit fullscreen mode

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

The above code will output the following

Sending email to
Sending email to
Unsubscribing subscriber1
Sending email to
Enter fullscreen mode Exit fullscreen mode

Top comments (0)