Design patterns Multiton Pool of Singletons (PHP example)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Multiton can be used as a container for singletons. This is Multiton implementation is a combination of Singleton and Pool patterns.

This is an example of how common Multiton abstract Pool class can be created:

abstract class MultitonPoolAbstract
{
    /**
     * @var array
     */
    protected static $instances = [];

    final protected function __construct() {}

    /**
     * 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()
    {
        $className = static::getClassName();

        if( !isset(self::$instances[$className]) ) {
            self::$instances[$className] = new $className;
        }

        return self::$instances[$className];
    }

    /**
     * Deletes a calling class object
     *
     * @return void
     */
    public static function deleteInstance()
    {
        $className = static::getClassName();

        if( isset(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() {}
}

This way we can instantiate a various Singleton pools.



Got any Design patterns Question?