Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Design patterns are reusable solutions to common problems. They're not code you copy-paste, but approaches that help organize and structure your code!
// IIFE creates private scope
const Calculator = (function() {
// Private variables
let result = 0;
// Private function
function log(operation, value) {
console.log(`${operation}: ${value}`);
}
// Public API
return {
add(value) {
result += value;
log('Add', value);
return this;
},
subtract(value) {
result -= value;
log('Subtract', value);
return this;
},
getResult() {
return result;
},
reset() {
result = 0;
return this;
}
};
})();
// Usage
Calculator.add(5).subtract(2).add(10);
console.log(Calculator.getResult()); // 13
// result is private - can't access directly
console.log(Calculator.result); // undefinedModern approach using closures (ES6 modules simulated)
class Database {
constructor() {
if (Database.instance) {
return Database.instance;
}
this.connection = 'Connected to DB';
Database.instance = this;
}
query(sql) {
console.log(`Executing: ${sql}`);
}
}
// Both get the same instance
const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true (same instance!)
// With ES6 modules (natural singleton)
// config.js
const config = {
apiUrl: 'https://api.example.com',
timeout: 5000
};
export default config;
// Any file importing config gets the same objectCreate objects without specifying exact class
class EventEmitter {
constructor() {
this.events = {};
}
on(event, callback) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(callback);
}
emit(event, data) {
const callbacks = this.events[event];
if (callbacks) {
callbacks.forEach(callback => callback(data));
}
}
off(event, callback) {
if (!this.events[event]) return;
this.events[event] = this.events[event].filter(
cb => cb !== callback
);
}
}
// Usage
const emitter = new EventEmitter();
// Subscribe
emitter.on('userLogin', (user) => {
console.log(`${user.name} logged in`);
});
emitter.on('userLogin', (user) => {
console.log(`Logging event for ${user.email}`);
});
// Emit event
emitter.emit('userLogin', { name: 'Alice', email: 'alice@example.com' });
// Both callbacks execute!Strategy, Decorator, and Command patterns
Combining patterns for app state
Encapsulate private data
ES6 modules are natural singletons
Create objects dynamically
Hide complex creation logic
Event-driven communication
Pub/Sub, React, Vue use this
One instance only
Config, state management