Home >Java >javaTutorial >How Can Java Enums Be Used to Implement the Singleton Design Pattern?

How Can Java Enums Be Used to Implement the Singleton Design Pattern?

Susan Sarandon
Susan SarandonOriginal
2024-12-15 02:22:09686browse

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!

Statement:
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