Singleton. private variable in the child of the Application class
In one of the answers on the forum there are these words:
It is better to create a private variable in the descendant of the Application class with a reference to the instance instead of a private static one in the sigleton class itself, if possible.
I'm confused, I can't understand the difference, please show me the code where everything is done according to this recommendation and the code where the variable is in the class itself.
Well, here is a variable in the class itself, it looks like this:
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance(){
if (null == instance){
instance = new Singleton();
}
return instance;
}
}
Variable in I don't understand what the Application
subclass looks like..Rather, because I do not understand what the benefits will be if you follow this recommendation.
The accepted answer in this question is the subject of my question Singleton in Android-evil?
1 answers
Application-the base class for storing the global state of the application. You can use it like this (you need to add android: name=".MyApplication " to the file section AndroidManifest.xml):
public class MyApplication extends Application {
private String mName;
@Override
public void onCreate() {
super.onCreate();
setName("Application instance is maintaining global application state");
}
public void setName(String name) {
mName = name;
}
public String getName() {
return mName;
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyApplication myApplication = (MyApplication)getApplication();
String s = myApplication.getName();
Log.d("TAG", s);
myApplication.setName("tester");
Log.d("TAG", myApplication.getName());
}
}
However, Google recommends using Singleton:
Note: There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), include Context.getApplicationContext() as a Context argument when invoking your singleton's getInstance() method.
Https://developer.android.com/reference/android/app/Application