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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You're being unnecessary complicated. To be immutable an object must be unmodifiable once it is created. That's normally interpreted to mean "modifiable only in the constructor", but if you were to create it another way that would still make it immutable. As long as your object cannot be modified after it is initialized then it is immutable. You can consider setting up the Singleton instance to be part of the initialization.
Most of the benefits of immutability are irrelevant in Singletons.
While this is the usual way of doing it, this is by no means the only way.
In Java 1.5 a new version of Singleton is the enum singleton pattern:
And since enums can have constructors, methods and fields, you can give them all the immutable state you want.
Reference:
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 (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)
The solution pointed out by Sean is a good way of initializing singletons if their creation is not expensive. If you want to "lazy loading" capability, look into the initialization on demand holder idiom.