Singleton on Android – evil?

Earlier, I used Singleton like this:

public class Singleton {      private static Singleton instance;       private Singleton (){      }       public static Singleton getInstance(){          if (null == instance){             instance = new Singleton();          }          return instance;      }  }

Earlier, I saw many examples of the use of this class in android applications and various reference books. But I came across an article that described the disadvantage of using such a Singleton in Android:

We create an instance of the Singleton class in the context of the current Activity, and if this Activity completes its work, then the class instance will be destroyed (not immediately, but when the Java garbage collector works). So, the next time getInstance () is called, the object will be recreated (the constructor will be called again). If we store some static variables or methods in the Singleton class, then this can simply be ignored.

Here is a link to the article

The rest of this article says that to avoid this error, you need to initialize a singleton in a subclass of the Application class:

public class MyApp extends Application {    @Override    public void onCreate() {       super.onCreate();       Log.w("MY", "onCreate MyApp");        MySingleton.initInstance();    } }

And singleton himself:

class MySingleton {     ...      public static void initInstance() {        Log.d("MY", "MySingleton::InitInstance()");        if (mInstance == null) {              mInstance = new MySingleton();        }     }      public static MySingleton getInstance() {       Log.d("MY", "MySingleton::getInstance()");       return mInstance;     }   ... }

Now, regardless of what activities are working, an instance of the MySingleton class will exist.

That is, is this a more correct use case for Singleton in Android? Does this method have any drawbacks? I would like to know your point of view.

Asked on February 4, 2020 in Programming.
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.