The Singleton Design Pattern is used to restrict the number of times a specific object can be created to a signle time by providing access to a shared instance of itself.
Singletons are exclusive to the one runtime. They should not be allowed to generate clones of themselves.
Singleton Design Pattern examples
Scenario A in Drupal
In the following example, Database::getConnection will return a singleton object.
We initialized the database connection object into the static variable 'self::$connections[$key][$target]' as a singleton object. Then it will be loaded from the static variable without creating a new one in the new function call.
Scenario A in PHP
In the following example, Database::getConnection will return a singleton database connection object.
The database connection object is stored in a static variable $_instance. So we can reuse it without creating a new database connection.
When to use Singleton Design Pattern?
The most common use of the Singleton Design Pattern is for architecting database connection objects. Creating a SQL connection is expensive, so we should create a singleton database connection instance then we can reuse it in somewhere else.