Junior
What is the Singleton 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 that instance.
In C#, this is usually implemented through a private constructor and a static property that creates and stores the single object:
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
// Private constructor prevents external instantiation
private Singleton() { }
public static Singleton Instance
{
get { return _instance; }
}
public void SomeMethod()
{
// Method logic
}
}
This approach ensures lazy initialization and thread safety (if other implementation options are used). Singleton is useful when a single shared resource is needed, such as configuration or connection manager.