前段时间我被问到使用单例而不是使用静态类有什么好处,这是我的回答:
静态类和单例之间的主要区别在于,对于静态类,您需要在代码中使用它对代码中的类名进行硬编码:
StaticClass::doSomething();
StaticClass::doSomethingElse();
Run Code Online (Sandbox Code Playgroud)
使用单例时,您只需要对类名称进行一次硬编码:
$singleton = SingletonClass::getInstance();
// other code does not need to know where $singleton came from,
// or even that class SingletonClass exists at all:
$singleton->doSomething();
$singleton->doSomethingElse();
Run Code Online (Sandbox Code Playgroud)
另一个重要的区别是单例类可以是层次结构的一部分,并且可以实现接口.
这并不意味着Singleton(模式)是好的,应该自由使用.但它比直接使用静态类更好.