标题翻译
Design patterns - Singleton and class loaders
问题
《Head First设计模式》一书提到了单例模式和类加载器。
> 问题:类加载器方面有什么需要注意的吗?我听说有可能两个类加载器最终会各自拥有它们自己的单例模式实例。
>
> 回答:是的,这是真的,因为每个类加载器定义了一个命名空间。
> 如果你有两个或更多的类加载器,你可以多次加载同一个类(在每个类加载器中加载一次)。现在,如果那个类恰好是一个单例模式,由于我们有多个版本的该类,我们也会有多个单例模式实例。因此,如果你在使用多个类加载器和单例模式,要小心。解决这个问题的一种方法是自己指定类加载器。
在哪种情况下,Java开发人员需要拥有多个类加载器?在哪种情况下,多个类加载器会对单例模式造成问题?
英文翻译
The Head First design patterns book mentions singletons and class loaders.
> Question : What about class loaders? I heard there is a chance that
> two class loaders could each end up with their own instance of
> Singleton.
>
> Answer : Yes, that is true as each class loader defines a namespace.
> If you have two or more class loaders, you can load the same class
> multiple times (once in each classloader). Now, if that class happens
> to be a Singleton, then since we have more than one version of the
> class, we also have more than one instance of the Singleton. So, if
> you are using multiple classloaders and Singletons, be careful. One
> way around this problem is to specify the classloader yourself.
In which situation do Java developers need to have multiple class loaders ? In which situations would multiple class loaders be a problem for singletons ?
专注分享java语言的经验与见解,让所有开发者获益!
评论