美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。
给我一些场景,除了使用单例是有意义的良好的老记录器。
美化的全局变量-变成一个美化的全局类。有人说打破面向对象设计。
给我一些场景,除了使用单例是有意义的良好的老记录器。
当前回答
Singleton类的主要目的是限制创建的实例数量,从而确保对资源的访问控制。
使用单例类不会产生内存空间浪费,因为它限制了实例的创建。因为对象的创建只会发生一次,而不是每次新请求时都创建。
单例类在内部使用互斥量,因此使其线程安全。这就是为什么多线程和数据库应用程序主要使用Java中的Singleton模式进行缓存、日志记录、线程池、配置设置等等
其他回答
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是横切层的一个很好的候选者。并为系统各层提供服务。
从本质上讲,单例包装了一个服务,例如日志记录、分析,并将其提供给系统中的其他层。
是的,单例需要遵循单一责任原则。