作为一种常用的设计模式,单例模式被广泛的使用。那么如何设计一个单例才是最好的呢?
通常我们会这么写,网上能搜到的例子也大部分是这样:
class A { protected static $_instance = null; protected function __construct() { //disallow new instance } protected function __clone(){ //disallow clone } public function getInstance() { if (self::$_instance === null) { self::$_instance = new self(); } return self::$_instance; } } class B extends A { protected static $_instance = null; }$a = A::getInstance(); $b = B::getInstance(); var_dump($a === $b);
class B extends A { protected static $_instance = null; }$a = A::getInstance(); $b = B::getInstance(); var_dump($a === $b);
bool(true)
class C { protected static $_instance = null; protected function __construct() {
} protected function __clone() { //disallow clone } public function getInstance() { if (static::$_instance === null) { static::$_instance = new static; } return static::$_instance; } } class D extends C { protected static $_instance = null; } $c = C::getInstance(); $d = D::getInstance(); var_dump($c === $d);
bool(false)
需要提醒的是,PHP中单例模式虽然没有像Java一样的线程安全问题,但是对于有状态的类,还是要小心的使用单例模式。单例模式的类会伴随PHP运行的整个生命周期,对于内存也是一种开销。