单例模式

类图

2024061016292196.png

代码示例

<?php
 
class Singleton
{
private static $instance = null;
 
private function __construct()
{
// Private constructor so nobody else can instance it
}
 
public static function getInstance()
{
if (self::$instance == null) {
self::$instance = new Singleton();
}
 
return self::$instance;
}
 
protected function __clone()
{
throw new \Exception('Cannot clone');
}
 
protected function __wakeup()
{
throw new \Exception('Cannot unserialize');
}
}
 
$singleton1 = Singleton::getInstance();
$singleton2 = Singleton::getInstance();
 
var_dump($singleton1 === $singleton2); // bool(true)

把单例当作基类来使用

<?php
 
class Singleton
{
private static $instances = [];
 
private function __construct()
{
// Private constructor so nobody else can instance it
}
 
public static function getInstance()
{
$subClass = static::class;
if (!isset(self::$instances[$subClass])) {
self::$instances[$subClass] = new static;
}
 
return self::$instances[$subClass];
}
 
protected function __clone()
{
throw new \Exception('Cannot clone');
}
 
protected function __wakeup()
{
throw new \Exception('Cannot unserialize');
}
}
 
class SingletonChildA extends Singleton
{
}
 
class SingletonChildB extends Singleton
{
}
 
$singletonA1 = SingletonChildA::getInstance();
$singletonA2 = SingletonChildA::getInstance();
 
$singletonB1 = SingletonChildB::getInstance();
$singletonB2 = SingletonChildB::getInstance();
 
var_dump($singletonA1 === $singletonA2); // true
var_dump($singletonB1 === $singletonB2); // true
var_dump($singletonA1 === $singletonB1); // false
var_dump($singletonA2 === $singletonB2); // false