Singleton class extension

I used to instantiate a singleton class as follows:

$Singleton = SingletonClassName::GetInstance();

and for the non singleton class:

$NonSingleton = new NonSingletonClassName;

I think we should not distinguish how we create an instance of a class, whether singleton or not. if I look at the perception of another class, I don't care if the class needs a single class or not. so i still don't like the way php handles a singleton class. I think, and I always want to write:

$Singleton = new SingletonClassName;

just another non-element class, is there a solution to this problem?

+5
source share
5 answers

, ( , ). .

, . , , singleton. , SPL-,

/**
 * Superclass for a wrapper around a singleton implementation
 *
 * This class provides all the required functionality and avoids having to copy and
 * paste code for multiple singletons.
 */
class SingletonWrapper{
    private $_instance;
    /**
     * Ensures only derived classes can be constructed
     *
     * @param string $c The name of the singleton implementation class
     */
    protected function __construct($c){
        $this->_instance = &call_user_func(array($c, 'getInstance'));
    }
    public function __call($name, $args){
        call_user_func_array(array($this->_instance, $name), $args);
    }
    public function __get($name){
        return $this->_instance->{$name};
    }
    public function __set($name, $value){
        $this->_instance->{$name} = $value;
    }
}

/**
 * A test singleton implementation. This shouldn't be constructed and getInstance shouldn't
 * be used except by the MySingleton wrapper class.
 */
class MySingletonImpl{
    private static $instance = null;
    public function &getInstance(){
        if ( self::$instance === null ){
            self::$instance = new self();
        }
        return self::$instance;
    }

    //test functions
    public $foo = 1;
    public function bar(){
        static $var = 1;
        echo $var++;
    }
}

/**
 * A wrapper around the MySingletonImpl class
 */
class MySingleton extends SingletonWrapper{
    public function __construct(){
        parent::__construct('MySingletonImpl');
    }
}

< >

$s1 = new MySingleton();
echo $s1->foo; //1
$s1->foo = 2;

$s2 = new MySingleton();
echo $s2->foo; //2

$s1->bar(); //1
$s2->bar(); //2
+2

: factory -method , :

$NonSingleton = NonSingletonClassName::createInstance();

Java ( Java), - .

+3

Singleton , . new , , , .

factory , . getInstance(), . " " " " , , .

+1

, new, , , . new , : -)

+1

All Articles