Home > Java > javaTutorial > How Does a Java Enum Implement the Singleton Pattern?

How Does a Java Enum Implement the Singleton Pattern?

DDD
Release: 2024-12-02 00:02:11
Original
688 people have browsed it

How Does a Java Enum Implement the Singleton Pattern?

Implementing Singleton with an Enum: Unveiling the Mechanism

The concept of implementing the Singleton design pattern using an enum in Java raises questions regarding instantiation. To delve into the inner workings, let's examine the code snippet provided:

public enum MySingleton {
     INSTANCE;   
}
Copy after login

Initially, it's imperative to note that the above enum declaration creates an implicit empty constructor. However, for clarity's sake, let's make it explicit:

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

Now, let's create a test class with a main() method to observe the behavior:

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

Upon executing this code, you'll witness the following output:

Here
INSTANCE
Copy after login

The question now arises: how is MySingleton instantiated? The answer lies in the nature of enum fields. They act as compile-time constants but are simultaneously instances of the corresponding enum type. Their construction occurs when the enum type is referenced for the very first time, which happens within the main() method in our case.

Therefore, it's crucial to understand that enum fields are essentially instances of their enum type, providing a convenient mechanism to enforce the Singleton pattern without the need for explicit instantiation using new.

The above is the detailed content of How Does a Java Enum Implement the Singleton Pattern?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template