DEV Community

loading...

Observer Pattern

Karthik Raja
I am a full stack developer
Originally published at codewithkarthik.com ・2 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

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

    def subscribe(self, observer):
        self.observers.append(observer)

    def unsubscribe(self, observer):
        self.observers.remove(observer)

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

class EmailSender(Subject):
    pass
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):
        self.send_email()

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

if __name__ == '__main__':
    email_sender = EmailSender()
    subscriber1 = EmailObserver("abc@gmail.com")
    subscriber2 = EmailObserver("efg@gmail.com")

    email_sender.subscribe(subscriber1)
    email_sender.subscribe(subscriber2)
    email_sender.notify()

    print("Unsubscribing subscriber1")
    email_sender.unsubscribe(subscriber1)
    email_sender.notify()
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 abc@gmail.com
Sending email to efg@gmail.com
Unsubscribing subscriber1
Sending email to efg@gmail.com
Enter fullscreen mode Exit fullscreen mode

Discussion (0)