Design patterns: Singleton

Mauto 2 min

The Singleton Pattern is used to ensure that a class has only one instance and provides a global point of access to that instance. This pattern is useful in situations where having multiple instances of a class could cause problems, consume too many resources, or simply make no sense.

Characteristics of the Singleton pattern

  1. Private constructor: Prevents the creation of multiple instances of the class
  2. Static getInstance() method: Checks whether an instance of the class already exists; if not, it creates a new one.
  3. Single instance: Every time getInstance() is called, it always returns the same instance, guaranteeing that there is only one.
  4. Cloning and unserialization forbidden: The pattern blocks cloning and unserialization, preventing the singleton instance from being duplicated.

PHP Example:

class Singleton {
    private static $instance;

    // The constructor is private to prevent the use of "new"
    private function __construct() {} 

    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
    
    // Prevents cloning of the instance
    private function __clone() {}

    // Prevents unserialization of the instance
    private function __wakeup() {}
}

// Usage
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

echo $instance1 === $instance2 ? "Same instance" : "Different instances";

Common use case

Imagine you’re developing an application that interacts with a database. Connecting to the database is an operation that can end up opening many connections, which can lead to performance problems, resource management issues, or even errors. In this context, the Singleton is useful because it guarantees that only one database connection is open.

BACK TO THE GUIDE

Copiato