Home >Java >javaTutorial >How to create a singleton enum in Java?
Singleton pattern limits the instantiation of a class to one object. INSTANCE is a public static final field that represents an enumeration instance. We can get an instance of a class using EnumSingleton.INSTANCE but it is better to encapsulate it in a getter in case we want to change the implementation.
There are a few reasons why we can use enums as singletons in Java
public enum Singleton { INSTANCE; private singleton() { } }
public enum EnumSingleton { <strong>INSTANCE</strong>; private String name; private int age; private void build(SingletonBuilder builder) { this.name = builder.name; this.age = builder.age; } public static EnumSingleton getSingleton() { <strong>// static getter</strong> return <strong>INSTANCE</strong>; } public void print() { System.out.println("Name: "+name + ", age: "+age); } public static class SingletonBuilder { private final String name; private int age; private SingletonBuilder() { name = null; } public SingletonBuilder(String name) { this.name = name; } public SingletonBuilder age(int age) { this.age = age; return this; } public void build() { EnumSingleton.INSTANCE.build(this); } } public static void main(String[] args) { new SingletonBuilder("Adithya").age(25).build(); EnumSingleton.getSingleton().print(); } }
Name: Adithya, age: 25
The above is the detailed content of How to create a singleton enum in Java?. For more information, please follow other related articles on the PHP Chinese website!