扩展单例类

cak*_*yus 5 php oop singleton extend

我曾经像这样创建一个单例类的实例:

$Singleton = SingletonClassName::GetInstance();
Run Code Online (Sandbox Code Playgroud)

对于非单身人士类:

$NonSingleton = new NonSingletonClassName;
Run Code Online (Sandbox Code Playgroud)

我认为我们不应该区分我们如何创建一个类的实例,无论这是一个单身是否.如果我看到其他班级的感知,我不在乎班级是否需要单身人士班级.所以,我仍然不满意php如何处理单例类.我想,我总是想写:

$Singleton = new SingletonClassName;
Run Code Online (Sandbox Code Playgroud)

只是另一个非单身人士类,有这个问题的解决方案吗?

Yac*_*oby 2

我不会推荐它,因为它会让你的代码更难理解(人们认为 new 意味着一个全新的对象)。但我不会推荐使用单例。

这段代码的基本思想是在单例周围有一个包装器。通过该包装器访问的所有函数和变量实际上都会影响单例。它并不完美,因为下面的代码没有实现很多魔术方法和 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');
    }
}
Run Code Online (Sandbox Code Playgroud)

例子

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

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

$s1->bar(); //1
$s2->bar(); //2
Run Code Online (Sandbox Code Playgroud)