單例登記處(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 儲存給定型別的多個實體。