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
Release: 2024-12-15 02:22:09
Original
691 people have browsed it

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

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

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

Output:

Instance created
INSTANCE
Copy after login

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!

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