问题描述
不可变对象仅由其构造函数初始化,而单例则由静态方法实例化.如何在Java中制作一个不变的单例?
An immutable object is initialized by its constuctor only, while a singleton is instantiated by a static method. How to make an immutable singleton in Java?
推荐答案
虽然这是通常的做法,但这绝不是唯一的方法.
While this is the usual way of doing it, this is by no means the only way.
在Java 1.5中,单例的新版本是枚举单例模式:
In Java 1.5 a new version of Singleton is the enum singleton pattern:
public enum Elvis{
INSTANCE // this is a singleton, no static methods involved
}
由于枚举可以具有构造函数,方法和字段,因此您可以为它们提供所需的所有不可变状态.
And since enums can have constructors, methods and fields, you can give them all the immutable state you want.
Classloader (thanks @Paŭlo Ebermann for reminding me): in this case use enums or the initialize-through-static-inner-class pattern. This is of course what is usually meant by a singleton.
Be Careful: enums and all other singletons are broken if loaded through multiple Classloaders.
ThreadLocal
)可以将上述所有内容设置为不可变的,每种方式各不相同(尽管对于容器管理的组件来说通常并不容易)
All of the above can be made immutable, each in their own way (although it's usually not easy for container-managed components)
这篇关于如何在Java中制作一个不变的单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!