单例登记处(PHP 示例)
此模式可用于包含已注册的单例人员池,每个单例都使用唯一 ID 进行区分:
abstract class MultitonRegistryAbstract
{
/**
* @var array
*/
protected static $instances = [];
/**
* @param string $id
*/
final protected function __construct($id) {}
/**
* Get class name of lately binded class
*
* @return string
*/
final protected static function getClassName()
{
return get_called_class();
}
/**
* Instantiates a calling class object
*
* @return static
*/
public static function getInstance($id)
{
$className = static::getClassName();
if( !isset(self::$instances[$className]) ) {
self::$instances[$className] = [$id => new $className($id)];
} else {
if( !isset(self::$instances[$className][$id]) ) {
self::$instances[$className][$id] = new $className($id);
}
}
return self::$instances[$className][$id];
}
/**
* Deletes a calling class object
*
* @return void
*/
public static function unsetInstance($id)
{
$className = static::getClassName();
if( isset(self::$instances[$className]) ) {
if( isset(self::$instances[$className][$id]) ) {
unset(self::$instances[$className][$id]);
}
if( empty(self::$instances[$className]) ) {
unset(self::$instances[$className]);
}
}
}
/*-------------------------------------------------------------------------
| Seal methods that can instantiate the class
|------------------------------------------------------------------------*/
final protected function __clone() {}
final protected function __sleep() {}
final protected function __wakeup() {}
}
这是简化的模式形式,可用于 ORM 存储给定类型的多个实体。