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