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

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


当前回答

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

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

其他回答

Singleton pattern is the most pervasive pattern in the Spring containerization approach. If we look at that in terms of architectural primitives - they form a blackboard graph of objects, to which every thread can read and write. They do the dramatic act of synchronizing between multiple threads. The very reason why multiple threads need to synchronize is because there are always resources that underlie a computational program, over which contention might occur. Consider what is called a 'last seat problem'. A flight is being booked, but there are multiple ways to do it. For simplicity lets assume that the data about the flight occupancy is stored in a flat file rather than a database. Now, if there are two threads, each functionally different (i.e represented by different endpoints in the webapp) and let one of these threads A, be the thread which a prospective passenger uses to make a booking and the other one B is which a flight manager uses to close the booking - virtually closing the boarding door. Then, if these threads do not use singleton, the flight object would be detached from the real resource out-there, which we say not the actual aeroplane but the entry in the flat file. The A thread would have reference to an object, while the passenger is still fighting a dilemma whether to fly or not and then finally when he makes up his mind, the B thread would already have closed the door. But the object referenced by the A thread would still show one more seat to go. Now, cutting out the RDBMS due to our initial assumption, the system would write a ticket for the passenger and issue it to him eventhough the boarding is closed. Now, in a singleton implementation, the moment the theread B accesses the system, the universal object Flight is updated with status closed. Hence, if the passenger finally makes up his mind and clicks confirm, he would get an error right away. All this would not have been possible without the singleton. Hence, singleton allows you to stay close to the resources and avoids thread contention.

读取应该只在启动时读取的配置文件,并将它们封装在Singleton中。

只读单例存储一些全局状态(用户语言、帮助文件路径、应用程序路径)是合理的。使用单例控制业务逻辑时要小心——单例几乎总是以多例告终

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

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

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

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

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

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

在我寻求真相的过程中,我发现实际上很少有“可接受的”理由使用Singleton。

在互联网上反复出现的一个原因是“日志记录”类(你提到过)。在这种情况下,可以使用Singleton来代替类的单个实例,因为日志类通常需要被项目中的每个类反复使用,令人作呕。如果每个类都使用这个日志类,依赖注入就变得很麻烦。

日志记录是“可接受的”单例的一个特定示例,因为它不会影响代码的执行。禁用日志记录,代码执行保持不变。启用它,一样。Misko在《单例的根本原因》中这样说:“这里的信息单向流动:从应用程序流向记录器。即使记录器是全局状态,由于没有信息从记录器流入应用程序,记录器也是可以接受的。”

我相信还有其他合理的原因。Alex Miller在“我讨厌的模式”中谈到,服务定位器和客户端UI也可能是“可接受的”选择。

阅读更多在Singleton我爱你,但你让我失望。