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 patte…


This content originally appeared on DEV Community and was authored by Aakash Kumar

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));
  }
}

Define the Observer Class:

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

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

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

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


This content originally appeared on DEV Community and was authored by Aakash Kumar


Print Share Comment Cite Upload Translate Updates
APA

Aakash Kumar | Sciencx (2024-07-02T09:00:00+00:00) Observer-Pattern | Javascript Design Pattern Simplified | Part 3. Retrieved from https://www.scien.cx/2024/07/02/observer-pattern-javascript-design-pattern-simplified-part-3/

MLA
" » Observer-Pattern | Javascript Design Pattern Simplified | Part 3." Aakash Kumar | Sciencx - Tuesday July 2, 2024, https://www.scien.cx/2024/07/02/observer-pattern-javascript-design-pattern-simplified-part-3/
HARVARD
Aakash Kumar | Sciencx Tuesday July 2, 2024 » Observer-Pattern | Javascript Design Pattern Simplified | Part 3., viewed ,<https://www.scien.cx/2024/07/02/observer-pattern-javascript-design-pattern-simplified-part-3/>
VANCOUVER
Aakash Kumar | Sciencx - » Observer-Pattern | Javascript Design Pattern Simplified | Part 3. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/02/observer-pattern-javascript-design-pattern-simplified-part-3/
CHICAGO
" » Observer-Pattern | Javascript Design Pattern Simplified | Part 3." Aakash Kumar | Sciencx - Accessed . https://www.scien.cx/2024/07/02/observer-pattern-javascript-design-pattern-simplified-part-3/
IEEE
" » Observer-Pattern | Javascript Design Pattern Simplified | Part 3." Aakash Kumar | Sciencx [Online]. Available: https://www.scien.cx/2024/07/02/observer-pattern-javascript-design-pattern-simplified-part-3/. [Accessed: ]
rf:citation
» Observer-Pattern | Javascript Design Pattern Simplified | Part 3 | Aakash Kumar | Sciencx | https://www.scien.cx/2024/07/02/observer-pattern-javascript-design-pattern-simplified-part-3/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.