单例模式:使用枚举版本

22 java singleton enums design-patterns

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

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

}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 32

public enum WirelessSensorFactory {
    INSTANCE;

    // all the methods you want
}
Run Code Online (Sandbox Code Playgroud)

这是你的单身人士:只有一个实例的枚举.

请注意,这个单例是线程安全的,而你的单例不是:两个线程可能都会进入竞争条件或可见性问题,并且都创建自己的单例实例.

  • 与任何其他枚举一样:WirelessSensorFactory.INSTANCE.someMethod() (2认同)

Old*_*eon 15

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

// 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;
}
Run Code Online (Sandbox Code Playgroud)


hov*_*yan 5

此处有效 Java 章节的在线参考。

public enum WirelessSensorFactory implements ISensorFactory { // change CLASS to ENUM here

        INSTANCE; //declare INSTANCE of the Enum

        //private static WirelessSensorFactory wirelessSensorFactory;

        // Remove the private construct - it's Enum, 
        // so you don't need to protect instantiations of the class
          //private WirelessSensorFactory(){
          //   System.out.println("WIRELESS SENSOR FACTORY");
          //}

        // You don't need to check if instance is already created, 
        // because it's Enum, hence you don't need the static var
          //public WirelessSensorFactory getWirelessFactory(){
          //    if(wirelessSensorFactory==null){
          //        wirelessSensorFactory= new WirelessSensorFactory();
          //    }
          //    return wirelessSensorFactory;
          //}

        /*
         * All other methods you need and 
         * implementation of all the Factory methods from your interface
         */

}
Run Code Online (Sandbox Code Playgroud)

用法:

WirelessSensorFactory.INSTANCE.<any public method>
Run Code Online (Sandbox Code Playgroud)