Java 单例模式:使用枚举版本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23721115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:52:22  来源:igfitidea点击:

Singleton Pattern: Using Enum Version

javadesign-patternsenumssingleton

提问by

I do not understand how to implement the EnumVersion of the Singletonpattern. 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.

我不明白如何实现模式的Enum版本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;
    }

}

采纳答案by JB Nizet

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.

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

回答by kennySystemExit

It is explained here: http://javarevisited.blogspot.sk/2012/07/why-enum-singleton-are-better-in-java.htmlSo, it can be simple done like this:

它在这里解释:http: //javarevisited.blogspot.sk/2012/07/why-enum-singleton-are-better-in-java.html所以,它可以像这样简单地完成:

public enum EasySingleton{
    INSTANCE;
}

and also with using abstract factory design pattern:

以及使用抽象工厂设计模式:

public class Singleton{
    //initailzed during class loading
    private static final Singleton INSTANCE = new Singleton();

    //to prevent creating another instance of Singleton
    private Singleton(){}

    public static Singleton getSingleton(){
        return INSTANCE;
    }
}

回答by hovanessyan

Online reference of the Effective Java chapter here.

此处有效 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
         */

}

Usage:

用法:

WirelessSensorFactory.INSTANCE.<any public method>

回答by OldCurmudgeon

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

回答by Mukesh

It is much easier than the all other Singleton creation version : -

它比所有其他单例创建版本要容易得多:-

public enum WirelessSensorFactory {

        INSTANCE;

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

}

回答by SUKHDEV PATIL

Following is a sample of singlton class,

以下是singlton类的示例,

public class SingletonClass {
    private static SingletonClass singletonInstance = null;

    private SingletonClass() {      
    }

    public static SingletonClass getSingletonInstance() {       
        if(singletonInstance == null) {
            synchronized (SingletonClass.class) {
                if(singletonInstance == null) {
                  singletonInstance = new SingletonClass();
                }
            }
        }
        return singletonInstance;
    }
}

This snippet will workout in the multithreaded environment too as it applies lock on the class.

此代码段也将在多线程环境中进行训练,因为它会在类上应用锁定。