用枚举实现单例(Java) [英] Implementing Singleton with an Enum (in Java)

查看:32
本文介绍了用枚举实现单例(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到可以使用 Enum 在 Java 中实现 Singleton,例如:

I have read that it is possible to implement Singleton in Java using an Enum such as:

public enum MySingleton {
     INSTANCE;   
}

但是,以上是如何工作的?具体来说,必须实例化 Object.这里,MySingleton 是如何被实例化的?谁在做 new MySingleton()?

But, how does the above work? Specifically, an Object has to be instantiated. Here, how is MySingleton being instantiated? Who is doing new MySingleton()?

推荐答案

这个,

public enum MySingleton {
  INSTANCE;   
}

有一个隐式的空构造函数.改为明确,

has an implicit empty constructor. Make it explicit instead,

public enum MySingleton {
    INSTANCE;
    private MySingleton() {
        System.out.println("Here");
    }
}

如果您随后添加了另一个具有 main() 方法的类,例如

If you then added another class with a main() method like

public static void main(String[] args) {
    System.out.println(MySingleton.INSTANCE);
}

你会看到

Here
INSTANCE

enum 字段是编译时常量,但它们是其 enum 类型的实例.而且,它们是在第一次引用枚举类型时构造的.

enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.

这篇关于用枚举实现单例(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆