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:

  1. Use the getInstance() method
  2. Use Singleton.INSTANCE
final Singleton singleton = Singleton.getInstance()
// OR
final Singleton singleton = Singleton.INSTANCE

Pros and cons

Pros:

  1. It is simple to write Enum Singletons
  2. Enums are inherently serializable
  3. No problems of reflection occur
  4. It is thread-safe to create enum instances

Cons:

  1. By default, enums do not support lazy loading
  2. Enums won’t allow changing a singleton object to multitonopposite of singleton, i.e., we can have more than one object of the class

Free Resources