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

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


当前回答

读取应该只在启动时读取的配置文件,并将它们封装在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或其他世界)。

当管理对整个应用程序共享的资源的访问时,应该使用单例,并且可能存在同一个类的多个实例将是破坏性的。确保对共享资源的访问线程安全是这种模式至关重要的一个很好的例子。

当使用单例时,你应该确保你不会意外地隐藏依赖关系。理想情况下,单例对象(就像应用程序中的大多数静态变量一样)在应用程序的初始化代码执行期间设置(c#可执行文件为静态void Main(), java可执行文件为静态void Main()),然后传递给所有其他需要它的实例化类。这有助于维护可测试性。

当需要管理共享资源时,可以使用单例。例如打印机假脱机程序。您的应用程序应该只有一个假脱机程序实例,以避免对相同资源的请求冲突。

或者数据库连接或者文件管理器等等。