|
| 1 | +// 📌 JavaScript Advanced - Design Patterns & Best Practices |
| 2 | + |
| 3 | +// Welcome to the thirteenth section of the JavaScript Advanced tutorial! |
| 4 | +// Here, you'll learn about common design patterns and best coding practices in JavaScript. |
| 5 | + |
| 6 | +// Singleton Pattern |
| 7 | +// Ensures that a class has only one instance and provides a global access point. |
| 8 | +class Singleton { |
| 9 | + constructor() { |
| 10 | + if (!Singleton.instance) { |
| 11 | + Singleton.instance = this; |
| 12 | + } |
| 13 | + return Singleton.instance; |
| 14 | + } |
| 15 | + sayHello() { |
| 16 | + console.log("Hello from Singleton!"); |
| 17 | + } |
| 18 | +} |
| 19 | +const instance1 = new Singleton(); |
| 20 | +const instance2 = new Singleton(); |
| 21 | +console.log(instance1 === instance2); // true |
| 22 | + |
| 23 | +// Factory Pattern |
| 24 | +// Creates objects without specifying the exact class. |
| 25 | +class User { |
| 26 | + constructor(name, role) { |
| 27 | + this.name = name; |
| 28 | + this.role = role; |
| 29 | + } |
| 30 | +} |
| 31 | +function userFactory(name, role) { |
| 32 | + return new User(name, role); |
| 33 | +} |
| 34 | +const admin = userFactory("Alice", "admin"); |
| 35 | +console.log(admin); |
| 36 | + |
| 37 | +// Observer Pattern |
| 38 | +// Allows objects to subscribe to changes in another object. |
| 39 | +class Subject { |
| 40 | + constructor() { |
| 41 | + this.observers = []; |
| 42 | + } |
| 43 | + subscribe(observer) { |
| 44 | + this.observers.push(observer); |
| 45 | + } |
| 46 | + notify(data) { |
| 47 | + this.observers.forEach((observer) => observer.update(data)); |
| 48 | + } |
| 49 | +} |
| 50 | +class Observer { |
| 51 | + update(data) { |
| 52 | + console.log("Received update:", data); |
| 53 | + } |
| 54 | +} |
| 55 | +const subject = new Subject(); |
| 56 | +const observer1 = new Observer(); |
| 57 | +subject.subscribe(observer1); |
| 58 | +subject.notify("New Data"); |
| 59 | + |
| 60 | +// Best Practices |
| 61 | +// - Use meaningful variable names |
| 62 | +// - Follow the DRY (Don't Repeat Yourself) principle |
| 63 | +// - Keep functions small and focused |
| 64 | +// - Use modular code with ES6 modules |
| 65 | +// - Handle errors properly using try/catch |
| 66 | +// - Optimize performance by avoiding unnecessary computations |
| 67 | + |
| 68 | +// 💡 Explore more patterns like MVC, Decorator, and Proxy for advanced design principles! |
0 commit comments