Is this a valid way to provide only one instance of an object in Java?

I get some strange errors with Mongodb, and in Mongodb, you have to mainatin Mongosingleton. I just wanted to make sure that it was really relevant.

public class DBManager {
    public static Mongo mongoSingleton = null;

    public static synchronized void getMongo(){
         if(mongoSingleton == null){
              mongoSingleton = new Mongo();
         }
         return mongoSingleton;
    }
}

Thank!

+3
source share
9 answers

You must set your public mongoSingleton member as private and hide the default constructor

So

private static Mongo mongoSingleton = null;

private Mongo() {

}

Mongo class implementation

public class Mongo {
    private static volatile Mongo instance;
    private Mongo() {
        ...
    }

    public static Mongo getInstance() {
        if (instance == null) {
            synchronized (Mongo.class) {
                if (instance == null) { // yes double check
                    instance = new Mongo();
                }
            }
        }

        return instance;
    }
}

Using

Mongo.getInstance();
+6
source

This is a typical Singleton pattern, but the preferred method in Java is to create an Enum:

public enum DBManager {
    INSTANCE;

    // implementation here
}

Then you can access the instance via:

DBManager.INSTANCE

, ( ) ClassLoader, JVM.

+5

, .

public class DBManager {
    private static Mongo mongoSingleton = new Mongo();

    public static Mongo getMongo(){
       return mongoSingleton;
    }
}
+1
 public static Mongo mongoSingleton = null;

 private static Mongo mongoSingleton = null;

, .

+1

, , - Singleton .

public final class DBManager {
    private static final Mongo mongoSingleton = new Mongo();

    private DBManager() {}

    public static Mongo getMongo() {
         return mongoSingleton;
    }
}

, , . Mongo , getMongo() .

Sun .

+1

private static final Mongo mongo = new Mongo() public static final Mongo mongo = new Mongo(). .

+1

, , , . synchronized , ( ) .

, , - Josh Bloch enum. enum , , .

public enum Mongo {

    INSTANCE;

    // instance fields, methods etc. as in any other class
}

private public static final, , , , .

, . INSTANCE , Mongo JVM, - , - , static .

, INSTANCE , INSTANCE:

Mongo mongo = Mongo.INSTANCE;

, .

+1

, , .

0

, , - http://www.javabeginner.com/learn-java/java-singleton-design-pattern

, .

public class DBManager {
private static Mongo mongoSingleton = null;

public static synchronized void getMongo(){
     if(mongoSingleton == null){
          mongoSingleton = new Mongo();
     }
     return mongoSingleton;
}

}

0

All Articles