What is a design pattern?
A design pattern is a proven, reusable solution to a common problem in software design. It is not code that you copy literally, but an idea that you adapt to your case.
Module pattern
It lets you encapsulate private state and expose only a public interface, taking advantage of closures.
const counter = (function () {
let count = 0; // private: nobody from outside can touch it
return {
increment() { count++; },
value() { return count; },
};
})();
counter.increment();
console.log(counter.value()); // 1
// console.log(counter.count); // undefined: it is private
Factory pattern
A factory is a function that creates objects, hiding the details of how they
are built. It is a more flexible alternative than using new directly.
function createUser(name, role) {
return {
name,
role,
greet() {
return `Hi, I am ${name} (${role})`;
},
};
}
const admin = createUser("Ana", "admin");
console.log(admin.greet());
The factory lets you decide what kind of object to create at runtime, without coupling the code to a specific class.
Examples
Module with private state
const bank = (function () {
let balance = 0;
return {
deposit(x) { balance += x; },
check() { return balance; },
};
})();
bank.deposit(100);
bank.deposit(50);
console.log("Balance:", bank.check());
Factory based on the type
function createShape(type, size) {
if (type === "square") return { area: () => size * size };
if (type === "circle") return { area: () => Math.PI * size * size };
}
console.log("Square area:", createShape("square", 4).area());