One instance to rule them all - but should it?
Imagine your app has multiple parts that need access to the same resource:
Without coordination, you'd create duplicates wastefully.
Creating multiple instances wastes memory and causes inconsistency.
Ensure a class has only ONE instance and provide a global access point to it.
Key characteristics:
new Singleton()getInstance() returns the instanceclass Logger {
private static instance = new Logger()
private constructor() {}
static getInstance() {
return Logger.instance
}
}
Created immediately when class loads.
class DatabasePool {
private static instance: DatabasePool
private constructor() {
// expensive setup
}
static getInstance() {
if (!DatabasePool.instance) {
DatabasePool.instance = new DatabasePool()
}
return DatabasePool.instance
}
}
Created only when first requested - saves resources if unused.
When you genuinely need one shared instance:
Use sparingly - only when multiple instances cause real problems.
Often called an "anti-pattern" due to:
Modern alternative: Dependency Injection
// Instead of this (Singleton):
const logger = Logger.getInstance()
logger.log('message')
// Do this (Dependency Injection):
class UserService {
constructor(private logger: Logger) {}
createUser(data) {
this.logger.log('Creating user')
}
}
// Create one logger, inject where needed
const logger = new Logger()
const userService = new UserService(logger)
Makes dependencies explicit and testable.
Remember: Just because you CAN make it a singleton doesn't mean you SHOULD.