Home >Java >javaTutorial >How Can Java Enums Be Used to Implement the Singleton Design Pattern?
Singleton Implementation with Enumerations
Singleton design patterns ensure that a class has only one instance, providing centralized access. An interesting approach to implementing Singletons in Java is through enumerations.
Consider the following enum:
public enum MySingleton { INSTANCE; }
How does this work, given that instantiation is typically performed using constructors? The answer lies in the implicit empty constructor for enum fields.
Explicit Construction
To make the instantiation process more explicit, we can define a private constructor:
public enum MySingleton { INSTANCE; private MySingleton() { System.out.println("Instance created"); } }
Instantiation
When subsequent code references the enum (such as MySingleton.INSTANCE), the constructor executes only once, establishing the singleton instance.
public static void main(String[] args) { System.out.println(MySingleton.INSTANCE); }
Output:
Instance created INSTANCE
Key Points
Enum fields are essentially instances of their enum type. They are constructed when the enum is referenced for the first time. This approach provides an elegant and type-safe means of implementing Singleton in Java.
The above is the detailed content of How Can Java Enums Be Used to Implement the Singleton Design Pattern?. For more information, please follow other related articles on the PHP Chinese website!