美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。

给我一些场景,除了使用单例是有意义的良好的老记录器。


当前回答

I use it for an object encapsulating command-line parameters when dealing with pluggable modules. The main program doesn't know what the command-line parameters are for modules that get loaded (and doesn't always even know what modules are being loaded). e.g., main loads A, which doesn't need any parameters itself (so why it should take an extra pointer / reference / whatever, I'm not sure - looks like pollution), then loads modules X, Y, and Z. Two of these, say X and Z, need (or accept) parameters, so they call back to the command-line singleton to tell it what parameters to accept, and the at runtime they call back to find out if the user actually has specified any of them.

在很多方面,处理CGI参数的单例方式与你每次查询只使用一个进程类似(其他mod_*方法不这样做,所以这很糟糕——因此这个参数说你不应该在mod_cgi世界中使用单例,以防你移植到mod_perl或其他世界)。

其他回答

我认为如果你的应用程序有多个层次,如表示,领域和模型。Singleton是横切层的一个很好的候选者。并为系统各层提供服务。

从本质上讲,单例包装了一个服务,例如日志记录、分析,并将其提供给系统中的其他层。

是的,单例需要遵循单一责任原则。

I use it for an object encapsulating command-line parameters when dealing with pluggable modules. The main program doesn't know what the command-line parameters are for modules that get loaded (and doesn't always even know what modules are being loaded). e.g., main loads A, which doesn't need any parameters itself (so why it should take an extra pointer / reference / whatever, I'm not sure - looks like pollution), then loads modules X, Y, and Z. Two of these, say X and Z, need (or accept) parameters, so they call back to the command-line singleton to tell it what parameters to accept, and the at runtime they call back to find out if the user actually has specified any of them.

在很多方面,处理CGI参数的单例方式与你每次查询只使用一个进程类似(其他mod_*方法不这样做,所以这很糟糕——因此这个参数说你不应该在mod_cgi世界中使用单例,以防你移植到mod_perl或其他世界)。

我不认为Singleton的场景与记录器、打印机池或任何示例相关。

单例决策的目的是优化硬件资源,而不是只有一个地方来控制任何记录器或打印机池

我个人认为单例应该在以下情况下使用:

我们正在谈论的对象总是以相同的方式实例化(即任何共享资源,如Logger或打印机池) 它被多次调用(这可以是100或1000,这与您的资源有关) 你的硬件资源是有限的(例如内存、处理能力等)。

如果你有大量的内存空间和处理能力,我认为没有必要使用单例。

Singleton将确保你只有一个实例,并且是惰性加载的,那么如果它被调用一百万次,你就只创建了一个对象。

当你加载一个配置属性对象时,无论是从数据库还是从文件中,将它作为一个单例都会有所帮助;没有理由在服务器运行时重新读取不会改变的静态数据。

管理到数据库的连接(或连接池)。

我还会使用它来检索和存储外部配置文件中的信息。