- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to make a singleton enum in Java?
The singleton pattern restricts the instantiation of a class to one object. INSTANCE is a public static final field that represents the enum instance. We can get the instance of the class with the EnumSingleton.INSTANCE but it is better to encapsulate it in a getter in case if we want to change the implementation.
There are a few reasons why we can use an enum as a singleton in Java.
Guaranteed one instance (Cannot instantiate more than one enum even through reflection).
Thread-safe.
Serialization.
Syntax
public enum Singleton { INSTANCE; private singleton() { } }
Example
public enum EnumSingleton { INSTANCE; private String name; private int age; private void build(SingletonBuilder builder) { this.name = builder.name; this.age = builder.age; } public static EnumSingleton getSingleton() { // static getter return INSTANCE; } 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(); } }
Output
Name: Adithya, age: 25
Advertisements