Menu
Coddy logo textTech

Observer Pattern

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 92 of 110.

The Observer pattern establishes a one-to-many relationship between objects: when one object (the subject) changes state, all its dependents (observers) are automatically notified. This is perfect for scenarios like UI updates, event systems, or any situation where multiple parts of your application need to react to changes.

The pattern involves two key roles: a Subject that maintains a list of observers and notifies them of changes, and Observers that register themselves and respond to updates:

abstract class Observer {
  void update(String message);
}

class NewsAgency {
  final List<Observer> _observers = [];
  String _latestNews = '';

  void subscribe(Observer observer) {
    _observers.add(observer);
  }

  void unsubscribe(Observer observer) {
    _observers.remove(observer);
  }

  void publishNews(String news) {
    _latestNews = news;
    for (var observer in _observers) {
      observer.update(_latestNews);
    }
  }
}

class NewsChannel implements Observer {
  final String name;
  NewsChannel(this.name);

  @override
  void update(String message) {
    print('$name received: $message');
  }
}

void main() {
  var agency = NewsAgency();
  var cnn = NewsChannel('CNN');
  var bbc = NewsChannel('BBC');

  agency.subscribe(cnn);
  agency.subscribe(bbc);

  agency.publishNews('Breaking news!');
  // CNN received: Breaking news!
  // BBC received: Breaking news!
}

When publishNews is called, the agency iterates through all subscribed observers and calls their update method. Observers can subscribe or unsubscribe at any time, making the system flexible and loosely coupled - the subject doesn't need to know the specific types of its observers.

challenge icon

Challenge

Easy

Let's build a stock price alert system using the Observer pattern! You'll create a system where a stock ticker notifies multiple investors whenever the price changes, allowing each investor to react to market updates in their own way.

You'll organize your code into two files:

  • stock_system.dart: Create your observer system here:
    • An abstract class Investor with a method void onPriceChange(String stockName, double price)
    • A class DayTrader that implements Investor. It has a name field and its onPriceChange method prints: [name] sees [stockName] at $[price] - Making quick trade!
    • A class LongTermInvestor that implements Investor. It has a name field and its onPriceChange method prints: [name] notes [stockName] at $[price] - Holding steady.
    • A class StockTicker (the subject) with:
      • A String stockName field
      • A private list to store subscribed investors
      • A subscribe(Investor investor) method to add an investor
      • An unsubscribe(Investor investor) method to remove an investor
      • An updatePrice(double newPrice) method that notifies all subscribed investors of the new price
  • main.dart: Import your stock system and demonstrate the Observer pattern in action:
    • Create a StockTicker for a stock named DART
    • Create a DayTrader named Alice and a LongTermInvestor named Bob
    • Subscribe both investors to the ticker
    • Update the price to 150.50 (both investors should be notified)
    • Print an empty line
    • Unsubscribe Alice from the ticker
    • Update the price to 155.75 (only Bob should be notified now)

This demonstrates how the Observer pattern creates a loosely coupled system - the StockTicker doesn't need to know whether it's notifying day traders or long-term investors, it just calls onPriceChange on whoever is subscribed!

Expected output:

Alice sees DART at $150.5 - Making quick trade!
Bob notes DART at $150.5 - Holding steady.

Bob notes DART at $155.75 - Holding steady.

Cheat sheet

The Observer pattern establishes a one-to-many relationship where a subject notifies all its observers when its state changes.

The pattern has two key roles:

  • Subject: Maintains a list of observers and notifies them of changes
  • Observer: Registers with the subject and responds to updates

Basic implementation:

abstract class Observer {
  void update(String message);
}

class Subject {
  final List<Observer> _observers = [];

  void subscribe(Observer observer) {
    _observers.add(observer);
  }

  void unsubscribe(Observer observer) {
    _observers.remove(observer);
  }

  void notifyObservers(String data) {
    for (var observer in _observers) {
      observer.update(data);
    }
  }
}

class ConcreteObserver implements Observer {
  final String name;
  ConcreteObserver(this.name);

  @override
  void update(String message) {
    print('$name received: $message');
  }
}

Key benefits:

  • Loose coupling between subject and observers
  • Observers can subscribe/unsubscribe dynamically
  • Subject doesn't need to know specific observer types

Try it yourself

import 'stock_system.dart';

void main() {
  // TODO: Create a StockTicker for a stock named 'DART'
  
  // TODO: Create a DayTrader named 'Alice'
  
  // TODO: Create a LongTermInvestor named 'Bob'
  
  // TODO: Subscribe both investors to the ticker
  
  // TODO: Update the price to 150.50 (both investors should be notified)
  
  // TODO: Print an empty line
  
  // TODO: Unsubscribe Alice from the ticker
  
  // TODO: Update the price to 155.75 (only Bob should be notified now)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming