SOLID & Design Patterns Interview Question #32
What is the Singleton Pattern?
Structural, Creational & Behavioral Patterns Junior Beginner
Quick Interview Answer
The Singleton Pattern ensures that a type has a single shared instance within a defined process or scope and provides access to that instance. Classic implementations manage construction themselves through a static property.
Detailed Explanation
The Singleton Pattern ensures that a type has a single shared instance within a defined process or scope and provides access to that instance. Classic implementations manage construction themselves through a static property.
In modern .NET applications, dependency injection lifetime management is usually preferable to hand-written global singletons because dependencies remain explicit and testing is easier.
Code Example
public sealed class AppClock
{
private static readonly Lazy<AppClock> _instance =
new(() => new AppClock());
private AppClock() { }
public static AppClock Instance => _instance.Value;
}