web-dev-qa-db-fra.com

Modèle singleton: utilisation de la version Enum

Je ne comprends pas comment implémenter la version Enum du modèle Singleton. Vous trouverez ci-dessous un exemple d'implémentation d'une approche "traditionnelle" utilisant le modèle Singleton. Je voudrais le changer pour utiliser la version Enum mais je ne sais pas comment.

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

}
22
user3287264
public enum WirelessSensorFactory {
    INSTANCE;

    // all the methods you want
}

Voici votre singleton: une énumération avec une seule instance.

Notez que ce singleton est thread-safe, tandis que le vôtre ne l'est pas: deux threads peuvent tous deux entrer dans une condition de concurrence critique ou un problème de visibilité et tous deux créent leur propre instance de votre singleton.

31
JB Nizet

Le modèle standard est de faire en sorte que votre énumération implémente une interface - de cette façon, vous n'avez pas besoin d'exposer plus de fonctionnalités en arrière-plan que vous n'en avez.

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

Référence en ligne du Effective Java chapitre ici .

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
         */

}

Utilisation:

WirelessSensorFactory.INSTANCE.<any public method>
4
hovanessyan

Il est expliqué ici: http://javarevisited.blogspot.sk/2012/07/why-enum-singleton-are-better-in-Java.html Donc, cela peut être simple fait comme ça :

public enum EasySingleton{
    INSTANCE;
}

et aussi en utilisant un modèle de conception d'usine abstrait:

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

C'est beaucoup plus facile que toutes les autres versions de création Singleton: -

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

}
0
Mukesh