Fundamentals 🌟
Introduction to the Singleton Pattern
Imagine a unique superhero who can only exist in a single instance throughout the universe. That's exactly what the Singleton pattern is! 🦸♂️
Why Do We Need a Unique Hero? 🤔
Here are some common scenarios:
- 🎮 A video game with multiple scoreboards... total confusion!
- 🏦 Multiple connections to the same database... what a waste of resources!
- ⚙️ Multiple different configurations... it's the gateway to chaos!
Singleton Superpowers
- 💪 Power of Uniqueness: A single instance, like one Batman for Gotham
- 🌟 Global Vision: Accessible from anywhere, like the Bat-Signal in the sky
- 🎯 Precision: A single source of truth, like Sauron's one ring
Basic Implementation
Our Hero's Code
1class Logger {
2 private static instance: Logger;
3 private logCount: number = 0;
4
5 private constructor() {
6 console.log('🚀 Logger awakens...');
7 }
8
9 public static getInstance(): Logger {
10 if (!Logger.instance) {
11 Logger.instance = new Logger();
12 }
13 return Logger.instance;
14 }
15
16 public log(message: string): void {
17 this.logCount++;
18 console.log(`📝 [Log #${this.logCount}] ${message}`);
19 }
20
21 public getStats(): string {
22 return `📊 Total logs: ${this.logCount}`;
23 }
24}
Simple Usage
1const logger = Logger.getInstance();
2logger.log('Our hero is ready!');
3console.log(logger.getStats());
Advanced Techniques 🚀
Thread-Safe Singleton
In a multi-threaded environment, our hero needs extra armor! Here's a thread-safe implementation:
1class ThreadSafeLogger {
2 private static instance: ThreadSafeLogger;
3 private static instanceLock = false;
4 private logs: string[] = [];
5
6 private constructor() {}
7
8 public static getInstance(): ThreadSafeLogger {
9 if (!ThreadSafeLogger.instanceLock) {
10 ThreadSafeLogger.instanceLock = true;
11 if (!ThreadSafeLogger.instance) {
12 ThreadSafeLogger.instance = new ThreadSafeLogger();
13 }
14 ThreadSafeLogger.instanceLock = false;
15 }
16 return ThreadSafeLogger.instance;
17 }
18}
Lazy Initialization Singleton 🦥
1class LazyLogger {
2 private static instance: LazyLogger;
3 private config: object;
4
5 private constructor(config: object) {
6 this.config = config;
7 }
8
9 public static getInstance(config?: object): LazyLogger {
10 if (!LazyLogger.instance && config) {
11 LazyLogger.instance = new LazyLogger(config);
12 }
13 if (!LazyLogger.instance) {
14 throw new Error('Logger needs configuration on first initialization!');
15 }
16 return LazyLogger.instance;
17 }
18}
Test-Ready Singleton 🧪
1class TestableLogger {
2 private static instance: TestableLogger;
3
4 private constructor() {}
5
6 public static getInstance(): TestableLogger {
7 if (!TestableLogger.instance) {
8 TestableLogger.instance = new TestableLogger();
9 }
10 return TestableLogger.instance;
11 }
12
13 // Special method for testing
14 public static resetInstance(): void {
15 TestableLogger.instance = null;
16 }
17}
Generic Singleton 🎭
1class GenericSingleton<T> {
2 private static instances: Map<string, any> = new Map();
3
4 protected constructor() {}
5
6 public static getInstance<T>(this: new () => T): T {
7 const className = this.name;
8 if (!GenericSingleton.instances.has(className)) {
9 GenericSingleton.instances.set(className, new this());
10 }
11 return GenericSingleton.instances.get(className);
12 }
13}
14
15// Usage
16class UserService extends GenericSingleton<UserService> {
17 public getUsers() {
18 return ['user1', 'user2'];
19 }
20}
21
22class ConfigService extends GenericSingleton<ConfigService> {
23 public getConfig() {
24 return { api: 'url' };
25 }
26}
Anti-Patterns and Pitfalls to Avoid ⚠️
- Tight Coupling
1// Avoid ❌
2class BadSingleton {
3 public static getInstance() {
4 // Code...
5 }
6 public doDirectDatabaseOperation() {
7 // Direct DB operation
8 }
9}
10
11// Prefer ✅
12interface DatabaseOperation {
13 execute(): void;
14}
15
16class GoodSingleton {
17 public static getInstance() {
18 // Code...
19 }
20 public executeOperation(operation: DatabaseOperation) {
21 operation.execute();
22 }
23}
- Global Mutable State
1// Avoid ❌
2class MutableSingleton {
3 private static instance: MutableSingleton;
4 public globalState: any = {};
5}
6
7// Prefer ✅
8class ImmutableSingleton {
9 private static instance: ImmutableSingleton;
10 private state: Readonly<any>;
11
12 public getState(): Readonly<any> {
13 return this.state;
14 }
15}
Complementary Patterns 🤝
Factory + Singleton
1interface Logger {
2 log(message: string): void;
3}
4
5class LoggerFactory {
6 private static instance: LoggerFactory;
7 private loggers: Map<string, Logger> = new Map();
8
9 private constructor() {}
10
11 public static getInstance(): LoggerFactory {
12 if (!LoggerFactory.instance) {
13 LoggerFactory.instance = new LoggerFactory();
14 }
15 return LoggerFactory.instance;
16 }
17
18 public getLogger(type: 'console' | 'file'): Logger {
19 if (!this.loggers.has(type)) {
20 this.loggers.set(type, this.createLogger(type));
21 }
22 return this.loggers.get(type);
23 }
24
25 private createLogger(type: 'console' | 'file'): Logger {
26 // Create specific logger
27 return type === 'console' ? new ConsoleLogger() : new FileLogger();
28 }
29}
Advanced Challenge 🎯
Create a Singleton that:
- Is thread-safe
- Uses lazy initialization
- Allows reset for testing
- Integrates a versioning system
Wrapping Up 🎬
The Singleton is a powerful pattern but requires thought in its implementation. The basic version is sufficient for simple cases, but advanced versions offer more robustness and flexibility for complex applications.
Pro Tips 💡
- Use lazy initialization for expensive resources
- Always consider testability
- Prefer dependency injection when possible
- Document your Singleton use cases well
Practical Exercises 🎮
- Implement a Singleton to manage application configurations
- Create a thread-safe Singleton with a message queue
- Develop a caching system using the Singleton pattern
Happy coding! 🚀