Sobes.tech
Junior — Middle

Explain the concept of the Singleton pattern and its main features.

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.

Main features of Singleton:

  • Single instance: the class controls the creation of the object to ensure there is only one.
  • Global accessibility: the instance is accessible from any part of the program.
  • Lazy initialization: the object is created upon first access (often).

Example 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;
        }
    }
}

This pattern is useful when you need to centrally manage resources or settings, such as a logger or configuration.

Explain the concept of the Singleton pattern and its… - sobes.tech