Sobes.tech
Junior — Middle

What is the main purpose of the Singleton pattern and when is it used?

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. This is useful when you need to control access to a resource, such as a database, application settings, or a logger.

Use Singleton when:

  • You need to restrict object creation to a single instance.
  • Centralized control of state or resources is required.
  • Global access to an object is necessary without passing it as a parameter.

Example in PHP:

class Singleton {
    private static ?Singleton $instance = null;

    private function __construct() {
        // private constructor
    }

    public static function getInstance(): Singleton {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

// Usage
$instance = Singleton::getInstance();