50 Mins advanced
24. Design Patterns
Architecture
Design Patterns
Design patterns are proven, reusable solutions to commonly occurring software architecture problems. Senior engineers use these to build scalable codebases.
๐งฑ The Module Pattern
Before ES6 modules existed, developers used closures (IIFEs) to create private variables and expose a public API. This prevents variables from polluting the global scope.
const ShoppingCart = (function() {
// Private Array
let cart = [];
return {
// Public API
addItem: function(item) {
cart.push(item);
},
getItems: function() {
return [...cart];
}
};
})();
ShoppingCart.addItem("Laptop");
console.log(ShoppingCart.getItems());
// console.log(ShoppingCart.cart); // Undefined! It is completely private.
Output[ 'Laptop' ]
๐ญ The Factory Pattern
Instead of using classes and the new keyword, a Factory pattern is simply a function that manufactures and returns new objects.
function createUser(name, role) {
return {
name: name,
role: role,
permissions: role === "admin" ? ["read", "write", "delete"] : ["read"]
};
}
const user1 = createUser("Alice", "admin");
const user2 = createUser("Bob", "guest");
console.log(user1.permissions);
console.log(user2.permissions);
Output[ 'read', 'write', 'delete' ]
[ 'read' ]
[ 'read' ]
๐ The Singleton Pattern
Ensures that a class or object has only one instance across the entire application (e.g., a Database connection pool or a global configuration object).
Knowledge Check
Ready to test your understanding of 24. Design Patterns?