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

How to create a singleton enum in Java?

WBOY
Release: 2023-08-29 10:21:06
forward
1131 people have browsed it

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() {
   }
}
Copy after login

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();
   }
}
Copy after login

Output

Name: Adithya, age: 25
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template