Using Object.freeze() in a Singleton design pattern ensures that the singleton instance cannot be modified once it has been created. This can be useful when you want to prevent changes to the Singleton instance, making sure it remains immutable and its properties are protected from being altered after initialization.
Example: Using Object.freeze() in a Singleton Pattern
Here’s how you can implement the Singleton pattern with Object.freeze():
** Singleton Design Pattern with Object.freeze()**
class ThemeManager {
constructor() {
if(ThemeManager.instance) {
this.theme = localStorage.getItem('theme') || 'light';
ThemeManager.instance = this;
}
return ThemeManager.instance;
}
setTheme(newTheme) {
this.theme = newTheme;
localStorage.setItem('theme', newTheme);
}
getTheme() {
return this.theme
}
}
const themeManager = new ThemeManager(); // Create an instance
Object.freeze(this); // Freeze the instance to make it immutable
export default themeManager; // Export the instance
Object.freeze(): The Object.freeze(this) call makes the instance immutable after it's created, meaning you cannot add new properties, modify existing properties, or change the state of the themeManager instance.If you try to modify themeManager after freezing, it won't allow changes, providing a layer of protection.It will throw error
Uncaught TypeError: Cannot add property theme, object is not extensible
Why Use Object.freeze()?
Immutability: Once an instance is created, it can't be modified. This is particularly useful when you want to prevent accidental changes to the Singleton object’s properties and methods.
Enforce Consistency: You ensure that the Singleton instance is always consistent and protected against any changes that might break the application logic.
Top comments (0)