Implementing Singleton with an Enum (in Java)

前端 未结 6 867
南笙
南笙 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

    Like all enum instances, Java instantiates each object when the class is loaded, with some guarantee that it's instantiated exactly once per JVM. Think of the INSTANCE declaration as a public static final field: Java will instantiate the object the first time the class is referred to.

    The instances are created during static initialization, which is defined in the Java Language Specification, section 12.4.

    For what it's worth, Joshua Bloch describes this pattern in detail as item 3 of Effective Java Second Edition.

提交回复
热议问题