Singleton Design Pattern ensures that a class has only one instance and provides global access to that instance
The Singleton pattern is a creational design pattern that restricts a class to a single instance and provides a global point of access to that instance. It's useful when exactly one object is needed to coordinate actions across the system.
This implementation demonstrates a thread-safe Singleton using double-checked locking pattern:
- Private Constructor: Prevents direct instantiation from outside the class
- Static Instance: Holds the single instance of the class
- Thread-Safe Access: Uses double-checked locking for thread safety
- Instance Counter: Demonstrates that only one instance is created
SingleTon- Sealed class implementing the Singleton pattern with:- Private static
Instancefield - Private static
Instancelockobject for thread synchronization - Private constructor that increments a counter
- Public static
GetInstance()method with double-checked locking PrintDetails()method for demonstration
- Private static
// Multiple parallel calls to get instance
Parallel.Invoke(
() => {
SingleTon.SingleTon ton = SingleTon.SingleTon.GetInstance();
ton.PrintDetails("From Teacher");
});
Parallel.Invoke(
() => {
SingleTon.SingleTon ton = SingleTon.SingleTon.GetInstance();
ton.PrintDetails("From Student");
});
// Output shows counter value is 1, proving only one instance was createdThe implementation uses double-checked locking pattern:
- First Check: Check if instance is null (without locking for performance)
- Lock: Acquire lock only if instance is null
- Second Check: Check again inside the lock to ensure thread safety
- Create: Create instance only if still null
- Sealed Class: Prevents inheritance
- Private Constructor: Prevents external instantiation
- Thread-Safe: Uses double-checked locking pattern
- Lazy Initialization: Instance created only when first requested
- Global Access: Single point of access through GetInstance()
- Ensures only one instance exists throughout application lifetime
- Provides global access point to the instance
- Lazy initialization saves memory until instance is needed
- Thread-safe implementation prevents race conditions
- Useful for logging, caching, database connections, etc.
- Database connection pools
- Logging services
- Configuration managers
- Cache managers
- Thread pools