Sobes.tech
Intern — Junior

Are you currently interested in new career opportunities?

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

Use Singleton when:

  • You want to restrict the creation of objects to a single instance.
  • You need centralized control over state or resources.
  • You want to ensure a global access point without passing the object around.

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();

This approach guarantees only one instance is created, and it is thread-safe without using synchronized.