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;
}
}
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With