while a singleton is instantiated by a static method
Although this is a common way to do this, this is far from the only way.
In Java 1.5, the new version of Singleton is a one-time renaming pattern:
public enum Elvis{ INSTANCE
And since enumerations can have constructors, methods, and fields, you can provide them with all the immutable state you want.
Link:
In addition, the term Singleton leaves room for interpretation. Singleton means that for a certain area there is exactly one object, but the scope can be several:
Java VM Classloader (thanks @ Paŭlo Ebermann for reminding me): in this case use enums or Initialize-static-inner class . This, of course, is what is usually meant by a single.
Be careful: enumerations and all other singletones are broken if they are loaded through multiple class loaders.- Enterprise Application (in this case, you need a container-controlled singleton such as Spring singleton bean ). This can be several objects on a VM or one object on several virtual machines (or one object on a virtual machine, of course).
- Theme (use
ThreadLocal ) - Request / Session (you will need a container to manage this Spring , Seam , and some others can do it for you)
- Did I forget something?
All of the above can be done unchanged, each in its own way (although for components controlled by containers, it is usually not easy)
source share