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

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

问题描述

我已经看到可以使用枚举在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()?

推荐答案

p>

This,

public enum MySingleton {
  INSTANCE;   
}

有一个隐式的空构造函数。让我们明确地说,

has an implicit empty constructor. Let's be explicit instead,

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

如果您再添加一个 main()

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

你会看到

Here
INSTANCE

枚举字段是编译时常数,但它们是枚举类型的实例。而且,当枚举类型被首次引用时,它们被构造。

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天全站免登陆