我不会推荐它,因为它会使你的代码更加难于理解(人们认为新指一个全新的对象)。但是,我不会重新使用单身人士。
此代码的基本思想是围绕单例包装。通过该包装器访问的所有函数和变量实际上都会影响单例。如下面的代码没有实现很多的魔术方法和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
中添加它不是完美的
Tthis不是问题 - 你抱怨说你不喜欢一个模式是如何完成的。 -1 – 2010-04-06 12:57:06
这是一个非常合理的问题。 +1,因为-1不是:P – Leo 2010-04-06 12:59:06
不要使用PHP? – Kevin 2010-04-06 12:59:36