Home >Java >javaTutorial >How Does a Java Enum Implement the Singleton Design Pattern?
Implementing Singleton with an Enum (in Java)
In the realm of software development, it is not uncommon to encounter scenarios where we need to ensure that a class has only one instance in memory. Singleton, a design pattern, caters to this requirement.
Consider the following Java implementation of Singleton using an enum:
public enum MySingleton { INSTANCE; }
On the surface, one might wonder how this actually works. After all, an object must be instantiated to exist. Here's the breakdown:
Implicit Constructor:
In reality, the enum declaration implicitly calls an empty constructor. However, this is not always clear from the code alone.
Explicit Constructor:
To make things more explicit, we can add a private constructor to the enum:
public enum MySingleton { INSTANCE; private MySingleton() { System.out.println("Here"); } }
Enum Constants and Construction:
Enum fields are essentially compile-time constants, but they are also instances of their enum type. The first time the enum type is referenced, these instances are constructed.
Main Method Demonstration:
If we create a main method in a separate class:
public static void main(String[] args) { System.out.println(MySingleton.INSTANCE); }
We can observe the following output:
Here INSTANCE
In this example, the instance "INSTANCE" is constructed the first time the enum is referenced in the main method.
The above is the detailed content of How Does a Java Enum Implement the Singleton Design Pattern?. For more information, please follow other related articles on the PHP Chinese website!