Created
May 16, 2025 00:49
-
-
Save night-fury-rider/f81c56c2e29ea5a3a1da410d30904fee to your computer and use it in GitHub Desktop.
Design Pattern - Observable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Stock { | |
| constructor(symbol) { | |
| this.symbol = symbol; | |
| this.price = 0; | |
| this.observers = []; | |
| } | |
| // Subscribe to stock price changes | |
| subscribe(observer) { | |
| this.observers.push(observer); | |
| return () => this.unsubscribe(observer); | |
| } | |
| // Unsubscribe from stock price updates | |
| unsubscribe(observer) { | |
| this.observers = this.observers.filter((obj) => obj !== observer); | |
| console.log(`${observer.name} has been unsubscribed successfully`); | |
| } | |
| // Notify all observers when price changes | |
| notify() { | |
| this.observers.forEach((observer) => observer.update(this)); | |
| } | |
| // Simulate a price change | |
| changePrice(newPrice) { | |
| this.price = newPrice; | |
| this.notify(); // Notify all observers | |
| } | |
| } | |
| class Investor { | |
| constructor(name) { | |
| this.name = name; | |
| } | |
| // Update method called when stock price changes | |
| update(stock) { | |
| console.log( | |
| `${this.name} has been notified: ${stock.symbol} is now at ₹${stock.price}` | |
| ); | |
| } | |
| } | |
| // Usage Example | |
| const sbiStock = new Stock("SBI"); | |
| const investor1 = new Investor("Yuvraj"); | |
| const investor2 = new Investor("Ganesh"); | |
| const unsubscribeInvestor1 = sbiStock.subscribe(investor1); | |
| const unsubscribeInvestor2 = sbiStock.subscribe(investor2); | |
| sbiStock.changePrice(1500); | |
| unsubscribeInvestor2(); // Ganesh unsubscribes | |
| // After 2 seconds, stock price is changed | |
| setTimeout(() => { | |
| sbiStock.changePrice(1600); // Only Yuvraj will be notified | |
| }, 2000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment