Browse Python Design Patterns & Architecture

Observer Pattern Use Cases and Examples in Python

Explore practical applications of the Observer pattern in Python with detailed examples including a Stock Market Ticker and Notification Systems.

5.7.4 Use Cases and Examples

The Observer pattern is a powerful behavioral design pattern that establishes a one-to-many relationship between objects. When the state of one object changes, all its dependents are notified and updated automatically. This pattern is particularly useful in scenarios where changes to one object need to be reflected across multiple others without tightly coupling them. In this section, we will explore practical applications of the Observer pattern in Python, focusing on two detailed examples: a Stock Market Ticker and Notification Systems.

Understanding the Observer Pattern

Before diving into the examples, let’s briefly recap the core components of the Observer pattern:

  • Subject: The object that holds the state and notifies observers of changes.
  • Observer: The object that wants to be informed about changes in the subject.
  • ConcreteSubject: A specific implementation of the subject.
  • ConcreteObserver: A specific implementation of the observer that reacts to changes in the subject.

The Observer pattern is widely used in various domains, such as GUI toolkits, event handling systems, and real-time data feeds. It promotes loose coupling and enhances the flexibility and scalability of a system.

Example 1: Stock Market Ticker

In the world of finance, stock prices fluctuate constantly, and traders need to be updated in real-time. The Observer pattern is an ideal fit for implementing a Stock Market Ticker, where multiple observers (traders, analysts, applications) need to be notified whenever a stock price changes.

Implementing a Stock Market Ticker

Let’s implement a simple Stock Market Ticker using the Observer pattern in Python. We’ll create a Stock class as the subject and a StockObserver class as the observer.

 1class Stock:
 2    def __init__(self, name, price):
 3        self._name = name
 4        self._price = price
 5        self._observers = []
 6
 7    def attach(self, observer):
 8        if observer not in self._observers:
 9            self._observers.append(observer)
10
11    def detach(self, observer):
12        try:
13            self._observers.remove(observer)
14        except ValueError:
15            pass
16
17    def notify(self):
18        for observer in self._observers:
19            observer.update(self)
20
21    @property
22    def price(self):
23        return self._price
24
25    @price.setter
26    def price(self, new_price):
27        if new_price != self._price:
28            self._price = new_price
29            self.notify()
30
31class StockObserver:
32    def __init__(self, name):
33        self._name = name
34
35    def update(self, stock):
36        print(f"{self._name} notified. {stock._name} price changed to {stock.price}")
37
38apple_stock = Stock('Apple', 150)
39trader1 = StockObserver('Trader 1')
40trader2 = StockObserver('Trader 2')
41
42apple_stock.attach(trader1)
43apple_stock.attach(trader2)
44
45apple_stock.price = 155
46apple_stock.price = 160

Explanation:

  • Stock Class: Acts as the subject. It maintains a list of observers and notifies them when the stock price changes.
  • StockObserver Class: Represents an observer that gets notified of stock price changes.
  • Usage: We create a Stock object for Apple and attach two StockObserver instances. When the stock price changes, both observers are notified.

Outcomes and Benefits

  • Improved Responsiveness: Observers are updated in real-time, ensuring that traders have the latest information.
  • Decoupled Components: Observers and the subject are loosely coupled, allowing for flexible system design and easy addition or removal of observers.

Example 2: Notification Systems

Notification systems are ubiquitous in modern applications, providing users with timely updates on various events. The Observer pattern is well-suited for implementing such systems, where multiple users (observers) need to be notified of events (subject).

Implementing a Notification System

Let’s create a simple notification system using the Observer pattern. We’ll have a NotificationService as the subject and User as the observer.

 1class NotificationService:
 2    def __init__(self):
 3        self._observers = []
 4
 5    def subscribe(self, observer):
 6        if observer not in self._observers:
 7            self._observers.append(observer)
 8
 9    def unsubscribe(self, observer):
10        try:
11            self._observers.remove(observer)
12        except ValueError:
13            pass
14
15    def notify(self, message):
16        for observer in self._observers:
17            observer.update(message)
18
19class User:
20    def __init__(self, username):
21        self._username = username
22
23    def update(self, message):
24        print(f"Notification for {self._username}: {message}")
25
26notification_service = NotificationService()
27user1 = User('Alice')
28user2 = User('Bob')
29
30notification_service.subscribe(user1)
31notification_service.subscribe(user2)
32
33notification_service.notify("New event available!")
34notification_service.notify("Your subscription is about to expire.")

Explanation:

  • NotificationService Class: Acts as the subject. It maintains a list of users (observers) and notifies them of new messages.
  • User Class: Represents an observer that receives notifications.
  • Usage: We create a NotificationService and subscribe two User instances. When a notification is sent, both users receive the message.

Outcomes and Benefits

  • Enhanced User Engagement: Users receive timely updates, keeping them informed and engaged.
  • Scalable System: New users can be easily added or removed from the notification list without affecting the system’s core functionality.

Try It Yourself

Now that we’ve explored two examples of the Observer pattern, let’s encourage you to try implementing it in your projects. Consider the following ideas:

  • Weather Monitoring System: Create a system where weather stations (subjects) update multiple displays (observers) with the latest weather data.
  • Chat Application: Implement a chat application where users (observers) receive messages from chat rooms (subjects) they are subscribed to.

Visualizing the Observer Pattern

To better understand the flow of the Observer pattern, let’s visualize it using a sequence diagram.

    sequenceDiagram
	    participant Stock as Stock
	    participant Observer1 as Trader 1
	    participant Observer2 as Trader 2
	
	    Stock->>Observer1: Notify price change
	    Stock->>Observer2: Notify price change

Diagram Description: This sequence diagram illustrates the notification process in the Stock Market Ticker example. When the stock price changes, the Stock object notifies all attached observers (Trader 1 and Trader 2).

References and Further Reading

Knowledge Check

To reinforce your understanding of the Observer pattern, consider the following questions:

  • How does the Observer pattern promote loose coupling in a system?
  • What are some potential drawbacks of using the Observer pattern?
  • How can you ensure that observers are notified in a specific order?

Embrace the Journey

Remember, mastering design patterns is a journey. As you continue to explore and implement the Observer pattern, you’ll discover new ways to enhance your applications’ responsiveness and scalability. Keep experimenting, stay curious, and enjoy the journey!

Quiz Time!

Loading quiz…
Revised on Thursday, April 23, 2026