Java Singleton – enum implementation
Singleton as enum is very simple to implement and very safe at the same time thanks to language guarantees for enum instantiation and serialization.
Properties of enum Singleton
- works in all versions since Java 5
- easy to implement
- is serializable out of the box
Complete example
In this example we’ll create enum Singleton with dummy constructor – just to show when it is initialized. Java language specification guarantees that it will be initialized only once, as we want:
package com.farenda.patterns.singleton; public enum SingletonEnum { INSTANCE; SingletonEnum() { System.out.println("Singleton enum initialization!"); } int sum(int x, int y) { System.out.printf("Called with x = %d, y = %d%n", x, y); return x+y; } public static void main(String[] args) { System.out.println("Is singleton: " + (SingletonEnum.INSTANCE == INSTANCE)); System.out.println("Sum: " + INSTANCE.sum(3, 4)); } }
The above code produces the following output:
Singleton enum initialization! Is singleton: true Called with x = 3, y = 4 Sum: 7
References:
- Effective Java (2nd Edition) by Josh Bloch
- GOF Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
- Java Singleton – static final implementation