Course contentsShow
← JavaScript
Lesson 2108 of 2,72344. Reactive PatternsFree lesson

The Observer Interface

Define the observer contract with an update method that receives notifications from subjects.

The Observer Interface

You'll learn how to define the contract that all observers must follow in the Observer Pattern.

What It Means

In the Observer Pattern, observers are the objects that want to be notified when something changes in the subject. The observer interface defines the contract these objects must follow—specifically, they must implement an update method that receives notifications from subjects.

Think of it like subscribing to a newsletter: the publisher (subject) needs to know how to send you updates, so every subscriber (observer) must provide a valid email address (the update method). Without that common interface, the publisher wouldn't know how to notify you.

The Observer Contract

The observer interface is simple but essential:

// The observer interface (conceptual)
class Observer {
  update(data) {
    // Receive and handle notifications from the subject
  }
}

Here's a concrete example:

class StockDisplay {
  update(stockData) {
    console.log(`Stock price updated: $${stockData.price}`);
  }
}

class AlertSystem {
  update(stockData) {
    if (stockData.price > 100) {
      console.log('ALERT: Price exceeded $100!');
    }
  }
}

// Both observers implement the same interface (update method)
const display = new StockDisplay();
const alerts = new AlertSystem();

The subject can now call observer.update(data) on any observer without needing to know what type of observer it is—it just trusts that the update method exists and follows the contract.

Key Takeaway: The observer interface requires all observers to implement an update method, creating a predictable contract that subjects can rely on to send notifications uniformly to any observer.