了解 Java 单例设计模式

Understanding Java singleton Design pattern

在阅读 Spring 框架的文档时,我遇到了以下问题:

Spring’s concept of a singleton bean differs from the Singleton pattern as defined in the Gang of Four (GoF) patterns book. The GoF Singleton hard-codes the scope of an object such that one and only one instance of a particular class is created per ClassLoader. The scope of the Spring singleton is best described as per container and per bean.

我不明白为什么每个 ClassLoader?为什么不根据整个应用程序或在上下文中将它们视为相同的东西?

因为在传统的单例中,你在单例中有一个静态变量class来保持单例。但是,由于您可以使用多个 ClassLoaders 加载相同的 class,因此它们将拥有自己的静态变量,并且可以自由创建自己的实例。

在大多数情况下这不是问题。