使用单例模式时是否存在差异?在类中保存静态实例并将其保存在返回实例的方法中时是否有任何区别?在类方法中使用静态实例还是在类中使用
例子: 课内。
class cExampleA {
static $mInstance;
protected function __construct() {
/* Protected so only the class can instantiate. */
}
static public function GetInstance() {
return (is_object(self::$mInstance) ? self::$mInstance : self::$mInstance = new self());
}
}
返回方法里面。
class cExampleB {
protected function __construct() {
/* Protected so only the class can instantiate. */
}
static public function GetInstance() {
static $smInstance;
return (is_object($smInstance) ? $smInstance : $smInstance = new self());
}
}
在一个侧面说明,使用三元运算符的例子有效(这意味着它可能会导致问题),并没有任何好处/倒台使用is_object超过isset?
更新:似乎唯一的区别是静态实例的范围?
,在跳出我这里的是,在照例a,静态属性是公开访问的主要事情。我猜这不是你想要的,所以你应该把它设置为'private'(尤其是因为你只用'is_object()'来检查它,这意味着它可以被任何东西覆盖。会更安全)。 – SDC
是的,我刚刚错过了私人。 instanceof听起来像个好主意,我总是忘记它。 – James
我必须说实话,我不知道在这种情况下是有区别的。我想这是其中有不止一种方法来实现同样的事情的情况之一。除非有人能以其他方式告诉我一个理由。对我来说,我会坚持使用私有财产(即exampleA),但我看不出为什么exampleB是错误的任何理由。 – SDC