Previously instead of using enums, I would do something like:
public static ExampleClass instance;
public ExampleClass(){
instance=this;
}
public static ExampleClass getInstance(){
return instance;
}
Then someone told me about a enum singleton:
public enum Example{
INSTANCE;
public static Example getInstance(){
return Example.INSTANCE;
}
In the first example I had to instantiate the object in order to create the instance. With an enum, I do not need to do that.. at least it appears. Can someone explain the reason behind this?
The Java compiler takes care of creating enum fields as static instances of a Java class in bytecode. Great blog post on it (not my blog) with bytecode here: http://boyns.blogspot.com/2008/03/java-15-explained-enum.html
If you disassemble the enum/class after you compile with-
javap Example
You get-
Compiled from "Example.java"
public final class Example extends java.lang.Enum<Example> {
public static final Example INSTANCE;
public static Example[] values();
public static Example valueOf(java.lang.String);
public static Example getInstance();
static {};
}
As you can see INSTANCE is a public static final field of Example class.
If you disassemble your EmployeeClass, you get-
public class ExampleClass {
public static ExampleClass instance;
public ExampleClass();
public static ExampleClass getInstance();
}
Do you see now the differences? It's essentially the same with minor differences.
我建议阅读Item 3: Enforce the singleton property with a private constructor or an enum type from Effective Java
Joshua Bloch解释了它是如何工作的以及为什么将枚举用作Singleton。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.