DEV Community

Cover image for Observer-Pattern | Javascript Design Pattern Simplified | Part 3
Aakash Kumar
Aakash Kumar

Posted on

Observer-Pattern | Javascript Design Pattern Simplified | Part 3

As a developer, understanding various JavaScript design patterns is crucial for writing maintainable, efficient, and scalable code. Here are some essential JavaScript design patterns that you should know:

Observer Pattern

The Observer pattern allows objects to notify other objects about changes in their state.

Example

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

addObserver(observer) {
this.observers.push(observer);
}

notifyObservers(message) {
this.observers.forEach(observer => observer.update(message));
}
}

class Observer {
update(message) {
console.log(Observer received: ${message});
}
}

const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();

subject.addObserver(observer1);
subject.addObserver(observer2);

subject.notifyObservers('Hello Observers!');`

Real World Example

Stock Market

Real-World Scenario: A stock market application where investors subscribe to stock updates. When the stock price changes, all subscribed investors are notified.

Define the Subject Class:

class Stock {
  constructor(symbol) {
    this.symbol = symbol;
    this.price = 0;
    this.observers = [];
  }

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

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

  setPrice(price) {
    this.price = price;
    this.notifyObservers();
  }

  notifyObservers() {
    this.observers.forEach(observer => observer.update(this.symbol, this.price));
  }
}
Enter fullscreen mode Exit fullscreen mode

Define the Observer Class:

class Investor {
  constructor(name) {
    this.name = name;
  }

  update(symbol, price) {
    console.log(`${this.name} notified: ${symbol} is now $${price}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Use the Observer Pattern:

const googleStock = new Stock('GOOGL');

const investor1 = new Investor('Alice');
const investor2 = new Investor('Bob');

googleStock.subscribe(investor1);
googleStock.subscribe(investor2);

googleStock.setPrice(1200);
// Alice notified: GOOGL is now $1200
// Bob notified: GOOGL is now $1200
Enter fullscreen mode Exit fullscreen mode

Use Cases of the Observer Pattern

1.Event Handling Systems: Used in systems that handle various events and notify subscribers about these events (e.g., event listeners in UI frameworks).

2.Real-time Data Streaming: Useful in applications that need to react to real-time data updates (e.g., stock price tickers, live sports scores).

3.MVC Architecture: Often used in the Model-View-Controller architecture to synchronize the view when the model changes.

4.Notification Systems: Implementing systems that notify users of changes or updates (e.g., social media notifications, email alerts).

5.State Management: Useful in state management libraries to manage and propagate state changes across components (e.g., Redux, MobX).

Conclusion

Understanding these design patterns and knowing when to apply them can greatly improve your coding skills and make you a more effective full-stack developer. They help in creating robust and maintainable code.

Mastering these patterns will help you build better software.

Happy Coding! πŸ§‘β€πŸ’»

Connect with Me πŸ™‹πŸ»: LinkedIn

Top comments (0)