Implementing Singleton with an Enum (in Java)

前端 未结 6 686
南笙
南笙 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:25

    Since Singleton Pattern is about having a private constructor and calling some method to control the instantiations (like some getInstance), in Enums we already have an implicit private constructor.

    I don't exactly know how the JVM or some container controls the instances of our Enums, but it seems it already use an implicit Singleton Pattern, the difference is we don't call a getInstance, we just call the Enum.

提交回复
热议问题