How to make a singleton enum in Java?

JavaObject Oriented ProgrammingProgramming

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
raja
Published on 02-Aug-2019 12:22:44
Advertisements