Module, Factory, Singleton
Module, Factory, Singleton
JavaScript provides different design patterns for organizing and structuring code
efficiently. Among them, Module, Factory, and Singleton are widely used for code
reusability, encapsulation, and efficient memory usage.
🔹 1. Module Pattern
📌 What is it?
The Module Pattern is used to encapsulate private and public methods inside a
function using closures. It prevents global scope pollution and allows controlled
access to variables.
return {
increment: function () {
count++;
console.log(`Count: ${count}`);
},
decrement: function () {
count--;
console.log(`Count: ${count}`);
},
getCount: function () {
return count;
},
};
})();
Counter.increment(); // Count: 1
Counter.increment(); // Count: 2
console.log(Counter.getCount()); // 2
✅ Benefits:
Encapsulation: Private variables are not accessible directly.
🔹 2. Factory Pattern
📌 What is it?
The Factory Pattern is used to create multiple objects using a common function
without using the new keyword. It helps avoid code duplication and makes
object creation more dynamic.
return {
name,
role,
greet: function () {
},
};
✅ Benefits:
Avoids the new keyword: Makes code simpler and more readable.
🔹 3. Singleton Pattern
📌 What is it?
The Singleton Pattern ensures that a class or function has only ONE instance
and provides a global point of access to it.
📌 Example: Database Connection Singleton
function createInstance() {
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
return instance;
},
};
})();
✅ Benefits:
Used for Shared Resources: Best for database connections, caching, etc.
🔥 Summary
🚀 Conclusion