5 Design Patterns Every Developer Should Know
· One min read
Design patterns are proven solutions to common programming challenges. Understanding these patterns can significantly improve your code quality and maintainability.
Singleton Pattern
The Singleton pattern ensures a class has only one instance while providing global access to this instance.
class Database {
private static instance: Database;
private constructor() {}
public static getInstance(): Database {
if (!Database.instance) {
Database.instance = new Database();
}
return Database.instance;
}
}
Observer Pattern
Keep objects informed of changes without tightly coupling them together.
class EventEmitter {
private listeners = {};
subscribe(event, callback) {
if (!this.listeners[event]) {
this.listeners[event] = [];
}
this.listeners[event].push(callback);
}
emit(event, data) {
if (this.listeners[event]) {
this.listeners[event].forEach(callback => callback(data));
}
}
}
Factory Pattern
Create objects without explicitly specifying their exact classes:
class UserFactory {
createUser(type) {
switch (type) {
case "admin":
return new AdminUser();
case "regular":
return new RegularUser();
default:
throw new Error("Invalid user type");
}
}
}