Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton Pattern: Using Enum Version

I do not understand how to implement the Enum Version of the Singleton pattern. Below is an example of implementing "traditional" approach using the Singleton pattern. I would like to change it to use the Enum version but I am not sure how.

public class WirelessSensorFactory implements ISensorFactory{

    private static WirelessSensorFactory wirelessSensorFactory;

    //Private Const
    private WirelessSensorFactory(){
        System.out.println("WIRELESS SENSOR FACTORY");
    }

    public static WirelessSensorFactory getWirelessFactory(){

        if(wirelessSensorFactory==null){
            wirelessSensorFactory= new WirelessSensorFactory();
        }

        return wirelessSensorFactory;
    }

}

2 Answers

public enum WirelessSensorFactory {
    INSTANCE;

    // all the methods you want
}

Here's your singleton: an enum with only one instance.

Note that this singleton is thread-safe, while yours is not: two threads might both go into a race condition or visibility problem and both create their own instance of your singleton.

like image 154
JB Nizet Avatar answered Sep 13 '25 02:09

JB Nizet


The standard pattern is to have your enum implement an interface - this way you do not need to expose any more of the functionality behind the scenes than you have to.

// Define what the singleton must do.
public interface MySingleton {

    public void doSomething();
}

private enum Singleton implements MySingleton {

    /**
     * The one and only instance of the singleton.
     *
     * By definition as an enum there MUST be only one of these and it is inherently thread-safe.
     */
    INSTANCE {

                @Override
                public void doSomething() {
                    // What it does.
                }

            };
}

public static MySingleton getInstance() {
    return Singleton.INSTANCE;
}
like image 42
OldCurmudgeon Avatar answered Sep 13 '25 03:09

OldCurmudgeon