php:单例VS全静态类?什么时候使用什么? [英] Php: singleton VS full static class? When use what?

查看:355
本文介绍了php:单例VS全静态类?什么时候使用什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解singleton强制创建一个类。但为什么一个实例存在,如果我不直接访问它?为什么这个模式,是不是更容易只使用完整的静态类与静态方法和数据?

I understand that singleton enforces a class to be created once. But why should an instance exists if I dont access it directly? Why is that pattern for, isn't it easier just use full static class with static methods and datas?

推荐答案

在静态类和单例之间,使用静态类,你需要在你的代码中使用它来硬编码类名:

The major difference between a static class and a singleton is that with the static class, you need to hardcode the class name in your code everywhere you use it:

StaticClass::doSomething();
StaticClass::doSomethingElse();

使用单例时,只需要对类名进行一次硬编码:

While with a singleton, you only need to hardcode the class name once:

$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();

另一个重要的区别是单例类可以是层次结构的一部分并且可以实现接口。

Another important difference is that singleton classes can be part of hierarchies and can implement interfaces.

这并不意味着Singleton(模式)是好的,应该自由使用。但它比直接使用静态类更好。

This does not mean that Singleton (the pattern) is good and should be used liberally. But it is better than using a static class directly.

这篇关于php:单例VS全静态类?什么时候使用什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆