This shot explains how to implement a singleton pattern using enum
in Java.
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.
enum
in java?Enum is a special Java type used to define collections of constants.
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:
getInstance()
methodSingleton.INSTANCE
final Singleton singleton = Singleton.getInstance()
// OR
final Singleton singleton = Singleton.INSTANCE
Pros:
enum
instancesCons:
enums
do not support lazy loading