Reputation: 106
I have some utils and workers in my project. All of these classes works as singleton. Suppose that I have multimple activities where this objects used but is there a difference between
private LocationWorker mLocationWorker;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
mLocationWorker = LocationWorker.getInstance();
and this?
LocationWorker mLocationWorker = LocationWorker.getInstance()
It's okay to get references to this objects before onCreate() method?
Upvotes: 0
Views: 1066
Reputation: 1385
I usually prefer the first approach
private LocationWorker mLocationWorker;
...
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_forecast);
mLocationWorker = LocationWorker.getInstance();
because the object will be created only when needed. In the second approach you are creating a singleton object. The object takes memory even before when it is needed. Some situations I prefer the first approach are:
If the object will be used in certain part of the class, you should consider declaring it inside that class.
Upvotes: 2
Reputation: 37645
It's okay to get references to this objects before onCreate() method?
Yes it is.
LocationWorker mLocationWorker = LocationWorker.getInstance();
should work fine.
However, since it is a singleton, I'm not sure there's much point saving a reference to it in a field. You could just do
LocationWorker.getInstance()
whenever you need it.
Upvotes: 1