How does an enum singleton function?

*爱你&永不变心* 提交于 2019-11-30 18:06:00

问题


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?


回答1:


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




回答2:


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.




回答3:


I suggest to read Item 3: Enforce the singleton property with a private constructor or an enum type from Effective Java by Joshua Bloch which explains how it works and why to use enum as a Singleton.



来源:https://stackoverflow.com/questions/18425693/how-does-an-enum-singleton-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!