美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。
给我一些场景,除了使用单例是有意义的良好的老记录器。
美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。
给我一些场景,除了使用单例是有意义的良好的老记录器。
当前回答
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.
其他回答
您可以在实现状态模式时使用单例(以GoF书中所示的方式)。这是因为具体的State类没有自己的状态,而是根据上下文类执行它们的操作。
你也可以让抽象工厂成为一个单例。
当你加载一个配置属性对象时,无论是从数据库还是从文件中,将它作为一个单例都会有所帮助;没有理由在服务器运行时重新读取不会改变的静态数据。
Singleton类的主要目的是限制创建的实例数量,从而确保对资源的访问控制。
使用单例类不会产生内存空间浪费,因为它限制了实例的创建。因为对象的创建只会发生一次,而不是每次新请求时都创建。
单例类在内部使用互斥量,因此使其线程安全。这就是为什么多线程和数据库应用程序主要使用Java中的Singleton模式进行缓存、日志记录、线程池、配置设置等等
在我寻求真相的过程中,我发现实际上很少有“可接受的”理由使用Singleton。
在互联网上反复出现的一个原因是“日志记录”类(你提到过)。在这种情况下,可以使用Singleton来代替类的单个实例,因为日志类通常需要被项目中的每个类反复使用,令人作呕。如果每个类都使用这个日志类,依赖注入就变得很麻烦。
日志记录是“可接受的”单例的一个特定示例,因为它不会影响代码的执行。禁用日志记录,代码执行保持不变。启用它,一样。Misko在《单例的根本原因》中这样说:“这里的信息单向流动:从应用程序流向记录器。即使记录器是全局状态,由于没有信息从记录器流入应用程序,记录器也是可以接受的。”
我相信还有其他合理的原因。Alex Miller在“我讨厌的模式”中谈到,服务定位器和客户端UI也可能是“可接受的”选择。
阅读更多在Singleton我爱你,但你让我失望。
我认为单例的使用与数据库中的多对一关系是一样的。如果代码中有许多不同的部分需要处理对象的单个实例,那么使用单例就很有意义了。