单例模式:使用枚举版本

2022-09-01 20:02:57

我不明白如何实现模式的版本。下面是使用单例模式实现“传统”方法的示例。我想将其更改为使用Enum版本,但我不确定如何。EnumSingleton

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;
    }

}

答案 1
public enum WirelessSensorFactory {
    INSTANCE;

    // all the methods you want
}

下面是你的单例:只有一个实例的枚举。

请注意,此单例是线程安全的,而您的单例不是:两个线程可能都处于争用条件或可见性问题,并且都创建自己的单例实例。


答案 2

标准模式是让你的枚举实现一个接口 - 这样你就不需要在幕后公开更多的功能。

// 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;
}

推荐