5.3以前也可實現,但代碼較繁瑣, 如下:
class MOrder extends SModel{
protected static $handle; //單例句柄
private function __construct(){
//something
}
/**
* 獲取本類單例的方法,公開
*
* @return MOrder
*/
public static function instance() {
if(self::$handle){
return self::$handle;
}
$class = __CLASS__;
self::$handle = new $class();
return self::$handle;
}
//otherthing
}
5.3增加延遲靜態綁定(這個詞真別扭)
代碼實現如下
class SModel {
/**
* 獲取單例句柄,返回具體模型類的實例對象
*/
protected static function instance() {
if(static::$handle){
return static::$handle;
}
$class = get_called_class();
static::$handle = new $class();
return static::$handle;
}
//父類something
}
class MGoods extends SModel{
/**
* 獲取本類單例的方法,公開
* @return MGoods
*/
public static function instance(){
return parent::instance();
}
protected static $handle; //單例句柄
protected function __construct(){
//something
}
//otherthing
}
通過修改,子類的實現代碼減少一部分,轉由父類實現
實話說,仍很麻煩,如果PHP自己實現singleton就好了.