Home >Java >javaTutorial >How to create a singleton enum in Java?

How to create a singleton enum in Java?

WBOY
WBOYforward
2023-08-29 10:21:061126browse

How to create a singleton enum in Java?

Singleton pattern limits the instantiation of a class to one object. INSTANCE is a public static final field that represents an enumeration instance. We can get an instance of a class using EnumSingleton.INSTANCE but it is better to encapsulate it in a getter in case we want to change the implementation.

There are a few reasons why we can use enums as singletons in Java

  • Guaranteed one instance (multiple enums cannot be instantiated even through reflection).
  • Thread safety.
  • Serialization.

Syntax

public enum Singleton {
   INSTANCE;
   private singleton() {
   }
}

Example

public enum EnumSingleton {
   <strong>INSTANCE</strong>;
   private String name;
   private int age;
   private void build(SingletonBuilder builder) {
      this.name = builder.name;
      this.age = builder.age;
   }
   public static EnumSingleton getSingleton() { <strong>// static getter</strong>
      return <strong>INSTANCE</strong>;
   }
   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

The above is the detailed content of How to create a singleton enum in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete