Sobes.tech
Junior — Middle

What is the purpose of the Singleton pattern in software architecture?

sobes.tech AI

Answer from AI

The Singleton pattern is designed to ensure that only one instance of a class exists in an application. This is useful when you need to centrally manage access to a resource, such as a database or configuration.

Main characteristics of Singleton:

  • Guarantees a single instance of the class.
  • Provides a global point of access to that instance.

Example in PHP:

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

    private function __construct() {
        // private constructor prevents external instantiation
    }

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

    public function doSomething() {
        echo "Performing an action";
    }
}

// Usage
$singleton = Singleton::getInstance();
$singleton->doSomething();

Thus, Singleton helps control object creation and prevents resource duplication.