php设计模式篇-单例模式
实现方式一
class Singleton {
protected static $instance = null;
final protected function __construct()
{
}
public static function getInstance()
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
protected function __clone()
{
// TODO: Implement __clone() method.
}
}
var_dump(Singleton::getInstance() === Singleton::getInstance());
实现方式二
三私一公和instanceof
私有静态变量
私有构造函数
私有克隆函数
公共静态方法
class signleton {
private static $instance;
private function __construct()
{
}
private function __clone()
{
}
public static function getInstance()
{
if(!self::$instance instanceof self){
self::$instance = new self();
}
return self::$instance;
}
}
本文深入探讨了PHP中单例模式的两种实现方法,详细解释了如何通过私有静态变量、私有构造函数、私有克隆函数及公共静态方法确保类的唯一实例,并提供了具体的代码示例。

203

被折叠的 条评论
为什么被折叠?



