我正在为PHP应用程序编写一些实用程序类,其中很多将是单例。发现自己一遍又一遍地重写相同的代码,并决定创建一个抽象基类Singleton
并对其进行子类化。只是想确保我已经做到了这一点!关于单例模式的澄清
abstract class Singleton
{
private static $instance = NULL;
public static final function getInstance()
{
if(self::$instance == NULL)
self::$instance = instantiate();
return self::$instance;
}
protected abstract static function instantiate();
}
class LogHelper extends Singleton
{
protected static final function instantiate()
{
return new LogHelper();
}
}
现在,如果我已经正确这个问题,我可以调用从任何地方LogHelper $LOGGER = LogHelper::getInstance()
在我的代码库,并获得参照相同的实例每一次,是吗?
这与Ruby提供的mixin类似。我也会遵循@ jesse的建议 – Wes 2011-04-15 21:20:44
[为什么Singletons在PHP中没有用处](http://gooh.posterous.com/singletons-in-php) – Gordon 2011-04-15 22:07:32