对单例模式的澄清
我正在为 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(),并且每次都获取对同一实例的引用,是吗?
I'm writing some utility classes for a PHP app and a lot of them will be singletons. Found myself re-writing the same code over and over, and decided to make an abstract base class Singleton
and subclass it. Just want to make sure I've done this correctly!
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();
}
}
Now, if I have done this correctly, I can call LogHelper $LOGGER = LogHelper::getInstance()
from anywhere in my codebase, and get a reference to the same instance every time, yes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可能需要将 getInstance() 方法定义为静态方法,以便无需实例化该类即可访问它们。然后,您将使用这个:
并且,您可能想要定义一个私有构造函数:
You will probably need to define your getInstance() methods as static so that you can access them without having to instantiate the class. Then, you'll use this:
And, you'll probably want to define a private constructor:
虽然单例乍一看似乎是理想的解决方案,但事实并非如此。了解注册表和依赖注入;当您开始单元测试时,它们将使您的生活变得更轻松。
While singletons seem like the ideal solution at first, they are not. Learn about registries and dependecy injection; they will make your life easier when you start unit testing.