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

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


当前回答

正如大家所说,共享资源——特别是不能处理并发访问的资源。

我所见过的一个具体例子是Lucene搜索索引写入器。

其他回答

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是横切层的一个很好的候选者。并为系统各层提供服务。

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

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

当您想要确保一个类将有一个实例,并且该实例将有一个全局访问点时,您可以使用单例设计模式。

假设您有一个应用程序,它需要数据库来处理CRUD操作。理想情况下,您应该使用与数据库相同的连接对象来访问数据库并执行CRUD操作。

因此,为了确保数据库类有一个对象,并且该对象将在整个应用程序中使用,我们实现了单例设计模式。

确保构造函数是私有的,并且提供了一个静态方法来提供对单例类的单个对象的访问

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

将特定的基础设施关注点配置为单例或全局变量是非常实用的。我最喜欢的例子是依赖注入框架,它使用单例作为框架的连接点。

在这种情况下,您将依赖于基础设施来简化库的使用并避免不必要的复杂性。