我不會推薦它,因爲它會使你的代碼更加難於理解(人們認爲新指一個全新的對象)。但是,我不會重新使用單身人士。
此代碼的基本思想是圍繞單例包裝。通過該包裝器訪問的所有函數和變量實際上都會影響單例。如下面的代碼沒有實現很多的魔術方法和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