简体   繁体   English

枚举单例如何运作?

[英]How does an enum singleton function?

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: 然后有人告诉我一个enum单身人士:

 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. Java编译器负责将字节字段创建为字节码中Java类的静态实例。 Great blog post on it (not my blog) with bytecode here: http://boyns.blogspot.com/2008/03/java-15-explained-enum.html 关于字节码的很棒的博客文章(不是我的博客): http//boyns.blogspot.com/2008/03/java-15-explained-enum.html

If you disassemble the enum/class after you compile with- 如果你在编译之后反汇编枚举/类,

javap Example javap示例

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. 如您所见, INSTANCEExample类的公共静态final字段。

If you disassemble your EmployeeClass, you get- 如果你拆卸你的EmployeeClass,你得到 -

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM