Friday, 3 January 2014

My singleton for Android

From Wikipedia, there are many way to creates an singleton in Java. The simplest and clearest version is the follow one:

public class SingletonDemo {
    private static SingletonDemo instance = null;

    private SingletonDemo() { }

    public static synchronized SingletonDemo getInstance() {
        if (instance == null) {
            instance = new SingletonDemo ();
}
return instance;
    }
}

But in most of the cases, it is not suitable for Android because the constructor requires the context. So, this is the singleton that I use:

public class SingletonDemo {
    private static SingletonDemo instance = null;
    private static Context context;

    /**
     * To initialize the class. It must be called before call the method getInstance()
     * @param ctx The Context used

     */
    public static void initialize(Context ctx) {
    context = ctx;
    }

    /**
     * Check if the class has been initialized
     * @return true  if the class has been initialized
     *         false Otherwise
     */
    public static boolean hasBeenInitialized() {
    return context != null;

    }

    /**
    * The private constructor. Here you can use the context to initialize your variables.
    */
    private SingletonDemo() {
        // Use context to initialize the variables.
    }

    /**
    * The main method used to get the instance
    */
    public static synchronized SingletonDemo getInstance() {
    if (context == null) {
    throw new IllegalArgumentException("Impossible to get the instance. This class must be initialized before");
    }

    if (instance == null) {
    instance = new SingletonDemo();
    }

    return instance;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException("Clone is not allowed.");
    }


}

Note that the method initialize could be called in the main class and the method getInstance could be called from other classes. This will fix the problem when the caller class requires the singleton but it does not have the context.

Finally the method hasBeenInitialized is uses to check if the class has been initialized. This will avoid that different instances have different contexts.

No comments:

Post a Comment