Observer pattern is a behavioral design pattern that allows one object to notify other objects about any events that happen to it. In this pattern, an object, known as the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.

Key Concepts

  • Subject: The object that maintains a list of its dependents and notifies them of any state changes.
  • Observer: The object that depends on the subject and is notified of any state changes.

Structure

Here is the basic structure of the Observer pattern:

  • Subject: It maintains a list of observers and provides methods to add, remove, and notify observers.
  • Observer: It defines an update method that is called by the subject when its state changes.

Example

Let's consider a simple example of a stock market system where a subject (stock) notifies its observers (investors) when the stock price changes.

class Stock:
    def __init__(self):
        self._observers = []
        self._price = 0

    def add_observer(self, observer):
        self._observers.append(observer)

    def remove_observer(self, observer):
        self._observers.remove(observer)

    def notify_observers(self):
        for observer in self._observers:
            observer.update(self)

    def set_price(self, price):
        self._price = price
        self.notify_observers()

class Investor:
    def update(self, stock):
        print(f"Stock price changed to: {stock._price}")

# Usage
stock = Stock()
investor1 = Investor()
investor2 = Investor()

stock.add_observer(investor1)
stock.add_observer(investor2)

stock.set_price(100)  # This will notify investor1 and investor2

Benefits

  • Decoupling: The subject and observer are decoupled, meaning they are not tightly coupled to each other.
  • Scalability: It is easy to add new observers without modifying the subject.
  • Flexibility: Observers can be notified at any time when the subject's state changes.

Further Reading

For more information on design patterns, you can visit our Design Patterns Tutorial.

![Observer Pattern Diagram](https://cloud-image.ullrai.com/q/Observer_Pattern Diagram/)