Junior
What is the Singleton design pattern?
sobes.tech AI
Answer from AI
The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it.
It is used when a single instance of a resource is required, for example:
- Configuration manager
- Database connection pool
- Logger
Implementations:
-
Lazy Initialization: The instance is created upon the first request.
public sealed class Singleton { private static Singleton? instance = null; private static readonly object lockObject = new object(); private Singleton() { } // Private constructor public static Singleton Instance { get { if (instance == null) { lock (lockObject) { if (instance == null) { instance = new Singleton(); } } } return instance; } } } -
Eager Initialization: The instance is created when the class is loaded.
public sealed class Singleton { private static readonly Singleton instance = new Singleton(); private Singleton() { } // Private constructor public static Singleton Instance { get { return instance; } } }Advantage: thread safety by default, simpler implementation. Disadvantage: the instance is created even if it is not used.
-
Using
Lazy<T>: .NET Framework provides built-in support for lazy initialization.public sealed class Singleton { private static readonly Lazy<Singleton> lazyInstance = new Lazy<Singleton>(() => new Singleton()); private Singleton() { } // Private constructor public static Singleton Instance { get { return lazyInstance.Value; } } }Advantage: thread safety and lazy initialization out of the box, cleaner code.
Advantages of Singleton:
- Control over the number of instances.
- Global access point.
- Lazy initialization (in some implementations).
Disadvantages of Singleton:
- May violate the single responsibility principle.
- Makes unit testing difficult.
- Can lead to tight coupling of code.