Sobes.tech
Junior — Middle

Explain the working principle of the Singleton pattern and its main purpose.

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.

The main purpose is to control object creation to prevent multiple instances, for example, for managing configuration, logging, or resource access.

Example implementation of Singleton in C#:

public class Singleton
{
    private static Singleton _instance;
    private static readonly object _lock = new object();

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_lock)
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }
}

Here, the constructor is private to prevent external instantiation, and access to the instance is through the static Instance property with double-checked locking for thread safety.