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

How Does a Java Enum Implement the Singleton Design Pattern?

Linda Hamilton
Release: 2024-12-01 20:01:20
Original
704 people have browsed it

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;
}
Copy after login

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");
    }
}
Copy after login

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);
}
Copy after login

We can observe the following output:

Here
INSTANCE
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template