如何在Java中制作一个不变的单例? [英] How to make an immutable singleton in Java?
问题描述
不可变对象仅由其构造函数初始化,而单例则由静态方法实例化.如何在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?
推荐答案
而单例由a实例化 静态方法
while a singleton is instantiated by a static method
虽然这是通常的做法,但这绝不是唯一的方法.
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.
参考:
- Java教程:枚举类型
- 有效的Java ,项目3
- Singleton(枚举方式) (WikiPedia)
- Java tutorial: Enum Types
- Effective Java, Item 3
- Singleton (the enum way) (WikiPedia)
此外,单例"一词还留出了一些解释的空间. Singleton表示每个定义的范围只有一个对象,但是范围可以是很多东西:
Also, the term Singleton leaves some room for interpretation. Singleton means that there is exactly one object per defined scope, but the scope can be a number of things:
-
Java VMClassloader (感谢@PaŭloEbermann提醒我):在这种情况下,请使用通过静态内部类初始化模式.当然,这通常是单身人士的意思.
小心:枚举和所有其他单例如果通过多个Classloader加载,则会被破坏. - 企业应用程序(在这种情况下,您需要一个容器管理的单例,例如
ThreadLocal
) - 请求/会话(同样,您需要一个容器来管理它,接缝,其他几个人也可以为您完成此操作
- 我忘记了什么吗?
Java VMClassloader (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.- Enterprise Application (in this case you need a container-managed singleton, e.g. a Spring singleton bean). This can be several objects per VM or one object per several VMs (or one Object per VM, of course)
- Thread (use a
ThreadLocal
) - Request / Session (again, you'll need a container to manage this, Spring, Seam and several others can do that for you)
- did I forget anything?
可以将上述所有内容设置为不可变的,每种方式各不相同(尽管对于容器管理的组件来说通常并不容易)
All of the above can be made immutable, each in their own way (although it's usually not easy for container-managed components)
这篇关于如何在Java中制作一个不变的单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!