Lädt...


🔧 Mastering Real-Time Magic: The Observer Pattern


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

What is the Observer Pattern ?

At its core, the Observer pattern establishes a one-to-many dependency between objects so that when one object (the subject) changes state, all its dependents (observers) are notified and updated automatically. This pattern is ideal for scenarios where an object's state change should trigger specific actions in other parts of the code.

Observer pattern schema

Real use case : Real-Time Dashboard

The Observer Class

class Observer {
  constructor() {
    this.observers = [];
  }

  subscribe(callback) {
    this.observers.push(callback);
  }

  unsubscribe(callback) {
    this.observers = this.observers.filter(observer => observer !== callback);
  }

  notify(data) {
    this.observers.forEach(observer => observer(data));
  }
}

export default Observer;

In this implementation, we've defined an Observer class with methods to subscribe, unsubscribe, and notify observers.

Integrating the Observer Pattern

Now, let's use the Observer pattern to create a real-time dashboard with three data sources: stock prices, weather updates, and news alerts.

Stock Price

const stockObserver = new Observer();

function updateStockPrices(price) {
  console.log(`Stock Price: $${price}`);
}

stockObserver.subscribe(updateStockPrices);

// Simulate real-time updates
setInterval(() => {
  const newPrice = Math.random() * 100;
  stockObserver.notify(newPrice);
}, 2000);

Weather Updates

const weatherObserver = new Observer();

function updateWeather(weatherData) {
  console.log(`Weather Update: ${weatherData}`);
}

weatherObserver.subscribe(updateWeather);

// Simulate real-time updates
setInterval(() => {
  const newWeather = 'Sunny';
  weatherObserver.notify(newWeather);
}, 3000);

News Alerts

const newsObserver = new Observer();

function updateNews(news) {
  console.log(`News Alert: ${news}`);
}

newsObserver.subscribe(updateNews);

// Simulate real-time updates
setInterval(() => {
  const headlines = ['Breaking News 1', 'Breaking News 2', 'Breaking News 3'];
  const randomNews = headlines[Math.floor(Math.random() * headlines.length)];
  newsObserver.notify(randomNews);
}, 5000);

By implementing the Observer pattern, we've achieved a real-time dashboard that updates stock prices, weather conditions, and news alerts as soon as new data is available.

Going further with a more complex example

// Subject - Blog class
class Blog {
  constructor() {
    this.subscribers = [];
  }

  // add a subscriber (observer)
  subscribe(subscriber) {
    this.subscribers.push(subscriber);
  }

  // remove a subscriber (observer)
  unsubscribe(subscriberToRemove) {
    this.subscribers = this.subscribers.filter(subscriber => subscriber !== subscriberToRemove);
  }

  // Notify when there is a new article
  publishNewArticle(article) {
    this.subscribers.forEach(subscriber => {
      subscriber.notify(article);
    });
  }
}

// Observer - Subscriber class
class Subscriber {
  constructor(name) {
    this.name = name;
  }

  // notification method
  notify(article) {
    console.log(`${this.name} got a notification : new article! - "${article}"`);
  }
}

// Let's create a blog
const myBlog = new Blog();

// With three random users
const subscriber1 = new Subscriber('Alice');
const subscriber2 = new Subscriber('Bob');
const subscriber3 = new Subscriber('Charlie');

// The subscribers join to the blog
myBlog.subscribe(subscriber1);
myBlog.subscribe(subscriber2);
myBlog.subscribe(subscriber3);

// New article!
myBlog.publishNewArticle('Les dernières tendances en programmation');

// Result : Each subscriber got a notification

// Unsubscribe a user
myBlog.unsubscribe(subscriber2);

// New article!
myBlog.publishNewArticle('Guide de démarrage rapide en développement web');

// Result : Only Alice AND Charlie got a notification.

Benefits of the Observer Pattern

1 - Real-Time Updates: The Observer pattern enables real-time updates across various parts of your application, providing a seamless and responsive user experience.

2 - Decoupled Code: Objects are loosely coupled, making it easy to add or remove observers without affecting other parts of the code.

3 - Customizable Reactions: Observers can define custom reactions to changes, allowing for flexibility and extensibility.

Conclusion

The Observer pattern is a valuable addition to your JavaScript toolkit, particularly when you need real-time updates and efficient communication between components. As demonstrated through our real-time dashboard example, it ensures that changes in one part of your application immediately affect other dependent parts, resulting in a more interactive and dynamic user experience.

My Linkedin
My X
My portfolio

...

🐧 Observer Pattern: Was steckt hinter dem Observer Design Pattern?


📈 61.23 Punkte
🐧 Server

🔧 Pub/Sub pattern vs Observer Pattern: what's the difference?


📈 43.26 Punkte
🔧 Programmierung

🔧 Observer-Pattern | Javascript Design Pattern Simplified | Part 3


📈 43.26 Punkte
🔧 Programmierung

🔧 Design Pattern #3 - Observer Pattern


📈 43.26 Punkte
🔧 Programmierung

🔧 Tìm Hiểu Về RAG: Công Nghệ Đột Phá Đang "Làm Mưa Làm Gió" Trong Thế Giới Chatbot


📈 39.49 Punkte
🔧 Programmierung

🔧 Observer Pattern for Beginners


📈 30.61 Punkte
🔧 Programmierung

🔧 Building a Reactive Store in React Using the Observer Design Pattern and Custom Hook


📈 30.61 Punkte
🔧 Programmierung

🔧 Understanding the Observer Design Pattern in Java


📈 30.61 Punkte
🔧 Programmierung

🔧 C# | Understanding the Observer Pattern


📈 30.61 Punkte
🔧 Programmierung

🔧 Understanding the Subject-Observer Pattern with RxDart in Dart


📈 30.61 Punkte
🔧 Programmierung

🔧 C# Delegates In Practice — Implementing Observer Pattern With Delegates


📈 30.61 Punkte
🔧 Programmierung

🔧 JavaScript Designs — Observer Pattern


📈 30.61 Punkte
🔧 Programmierung

🔧 Kotlin Design Patterns: Simplifying the Observer Pattern


📈 30.61 Punkte
🔧 Programmierung

🔧 Mastering the Strategy Pattern: A Real-World Example in E-commerce Shipping with Java


📈 30.08 Punkte
🔧 Programmierung

📰 Apple: Magic Keyboard, Magic Mouse und Magic Trackpad immer noch mit Lightning unterwegs


📈 27.98 Punkte
📰 IT Nachrichten

🍏 Magic Mouse, Magic Keyboard, Magic Trackpad didn't get USB-C -- but it's still coming


📈 27.98 Punkte
🍏 iOS / Mac OS

📰 Space Gray: Magic Mouse, Magic Keyboard und Magic Trackpad in Sonderfarbe werden eingestellt


📈 27.98 Punkte
📰 IT Nachrichten

📰 Apple stellt Magic Keyboard, Magic Trackpad und Magic Mouse in Spacegrau ein


📈 27.98 Punkte
📰 IT Nachrichten

🔧 Infinite Scrolling: Mastering the Intersection Observer API By Making Seamless Infinite Scroll like a Pro


📈 27.67 Punkte
🔧 Programmierung

🔧 Infinite Scrolling: Mastering the Intersection Observer API By Making Seamless Infinite Scroll like a Pro


📈 27.67 Punkte
🔧 Programmierung

🔧 Mastering Intersection Observer: Enhance Your Web Experiences


📈 27.67 Punkte
🔧 Programmierung

🔧 The Observer Effect Unveiling the Quantum Magic of Human Consciousness


📈 27.3 Punkte
🔧 Programmierung

🔧 Service: O pattern que virou anti-pattern


📈 25.29 Punkte
🔧 Programmierung

🔧 Design Pattern #5 - Adapter Pattern


📈 25.29 Punkte
🔧 Programmierung

🔧 Module-Pattern | Javascript Design Pattern Simplified | Part 4


📈 25.29 Punkte
🔧 Programmierung

🔧 Decorator-Pattern | Javascript Design Pattern Simplified | Part 5


📈 25.29 Punkte
🔧 Programmierung

🔧 Factory-Pattern | Javascript Design Pattern Simplified | Part 2


📈 25.29 Punkte
🔧 Programmierung

🔧 Singleton-Pattern | Javascript Design Pattern Simplified | Part 1


📈 25.29 Punkte
🔧 Programmierung

🔧 Design Pattern #4 - Publisher/Subscriber Pattern


📈 25.29 Punkte
🔧 Programmierung

🔧 Design Pattern #2 - Facade Pattern


📈 25.29 Punkte
🔧 Programmierung

🔧 Go program pattern 01: Functional Options Pattern


📈 25.29 Punkte
🔧 Programmierung

🔧 A transição do Higher-Order Component pattern para o React Hooks pattern


📈 25.29 Punkte
🔧 Programmierung

📰 Neu in .NET 7 [5]: List Pattern und Slice Pattern mit C# 11


📈 25.29 Punkte
📰 IT Nachrichten

🔧 C# Pattern Matching Inside Out: Kompakter und prägnanter C#-Code durch Pattern Matching


📈 25.29 Punkte
🔧 Programmierung

matomo