How to use the singleton pattern using enum in Java
This shot explains how to implement a singleton pattern using enum in Java.
What is the singleton design pattern?
Singleton is a creational design pattern that ensures only one object of its kind exists and gives other code a single point of access to it.
What is enum in java?
Enum is a special Java type used to define collections of constants.
How to implement singleton using enum
In the code below we define a Singleton enum, consisting of methods to connect to the database. Similarly, the enum can have any number of methods.
enum Singleton
{
INSTANCE;
private final Client dbClient;
Singleton()
{
dbClient = Database.getClient();
}
public static Singleton getInstance()
{
return INSTANCE;
}
public Client getClient()
{
return dbClient;
}
}
There are two ways get an instance of the enum above:
- Use the
getInstance()method - Use
Singleton.INSTANCE
final Singleton singleton = Singleton.getInstance()
// OR
final Singleton singleton = Singleton.INSTANCE
Pros and cons
Pros:
- It is simple to write Enum Singletons
- Enums are inherently serializable
- No problems of reflection occur
- It is thread-safe to create
enuminstances
Cons:
- By default,
enumsdo not support lazy loading - Enums won’t allow changing a singleton object to
multiton opposite of singleton, i.e., we can have more than one object of the class