Sample code for Singleton implementation using enum

One of the Java programming classics, Effective Java, recommends using ʻenum to implement a Singleton ("Item 4: Enforce singleton characteristics with a private constructor or enum type"). The other day I had the opportunity to implement Singleton using ʻenum in my work, so I would like to keep the sample code.

Singleton.java


public enum Singleton {
    
    /**Must not be called from outside the class. */
    INSTANCE;
    
    private String field;
    
    /**
     *De facto constructor.
     *Only this method should be used to get the instance.
     * @return instance
     */
    public static Singleton getInstance() {
        if (INSTANCE.field == null) {
            INSTANCE.field =  "field";
        }
        return INSTANCE;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }
}

Main.java


public class Main {
    public static void main(String[] args) {
        Singleton instance1 = Singleton.getInstance();
        System.out.println(instance1.getField()); //=> field
        
        instance1.setField("changed field");
        
        //It looks like it's creating another instance,
        //In fact, they are using the same instance.
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance2.getField()); //=> changed field
    }
}

With the method using class, there are more points to consider especially in parallel programming, and the implementation becomes complicated proportionally, but with ʻenum, it is possible to realize Singleton very simply. I can do it. However, this usage deviates from the original usage of ʻenum-it seems like a "tricks", so "interface that becomes a singleton just by implementing" is the standard library. I wish I had it in the next section (´ ・ ω ・ `)

Recommended Posts

Sample code for Singleton implementation using enum
Sample code using Minio from Java
Sample code collection for Azure Java development
Minimal template code for Android development, RecyclerView implementation
Java sample code 02
Java sample code 03
[Java] Convert DB code to code value using enum
Java sample code 04
Sample code for search using QBE (Query by Example) of Spring Data JPA
Java sample code 01
Sample code for log output by Java + SLF4J + Logback
GUI sample using JavaFX
Apache beam sample code
Database implementation using Realm
Create QR code for Google Authenticator using ZXing in Java
Sample code for basic mocking and testing with Mockito 3 + JUnit 5