Day 41 Design Patterns — Module Pattern
Design patterns reusable solutions hain common programming problems ke liye. Module pattern se code ko private aur public parts mein organize karte hain — encapsulation ka practical implementation.
Module Pattern (IIFE)
Immediately Invoked Function Expression se private scope banao.
const ShoppingCart = (() => {
// Private — bahar se accessible nahi
let items = [];
let discount = 0;
function calculateTotal() {
return items.reduce((sum, item) => sum + item.price, 0) * (1 - discount);
}
// Public API
return {
addItem(item) {
items.push(item);
console.log(`Added: ${item.name}`);
},
removeItem(id) {
items = items.filter(i => i.id !== id);
},
setDiscount(pct) { discount = pct / 100; },
getTotal() { return calculateTotal(); },
getItems() { return [...items]; } // copy — original safe!
};
})();
ShoppingCart.addItem({ id: 1, name: "Shirt", price: 1500 });
console.log(ShoppingCart.getTotal()); // 1500
// ShoppingCart.items — undefined (private!)
🎯 Practice Challenge
BankAccount module banao with private balance. deposit(), withdraw(), getBalance() public methods. Overdraft protection add karo.