Implementing Singleton with an Enum (in Java)

前端 未结 6 839
南笙
南笙 2020-11-22 11:44

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

public enum MySingleton {
     INSTANCE;   
}         


        
6条回答
  •  眼角桃花
    2020-11-22 12:36

    This,

    public enum MySingleton {
      INSTANCE;   
    }
    

    has an implicit empty constructor. Make it explicit instead,

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

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

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

    You would see

    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.

提交回复
热议问题