开发者

android singleton vs static methods

I need to load some files and store them in a static variable.

The load and getter methods are required in almost every Activity.

I was going to make the methods static, but some blogger dis-liked it.

Main advantages and disadvantages for both approaches for me are as follows.

singleton

advantages : Ability to keep pol开发者_开发技巧ymorphism.

disadvantages : Have to call getInstantace methods in every Activity.

static method is vice-versa.

Please guide me in choosing between the two or any other approach.

Any help would be appreciated.


I would avoid using Static variables in Android, because Android often clears all Static data from your class if your app is paused and the phone is short on resources, leading to unexpected Null Pointer Exceptions. Search Google for "Android Static Null" for a better explanation.

Either ways (Static methods or Singletons), you should make sure your app has the ability to save state and restore it in case Android clears your static variables.


You can find "some blogger" who pretty much dislikes anything. There's nothing wrong with static methods, so long as any state they operate on is local to the method/passed in with each call (same caveat applies for instance methods on a singleton).

Either approach should be fine, just pick the one you prefer. As a general rule of thumb, go with static methods if your singleton instance would not be holding any state that is potentially mutable at runtime. Otherwise, if the singleton is meant to hold state and not just serve as a repository for a handful of utility methods, then make it a singleton.

The only halfway reasonable argument against using static methods that I have come across is that static methods are problematic to mock-out for unit-testing purposes. But my guess is that you are probably not doing mock unit-testing, and I think the value of testing with mock objects is generally overstated when you look at the value that comes out of it relative to the amount of work that goes into setting up the test case(s).


The proper way will be to use dependency injection. There is a question here that discusses your alternatives.

For me singleton and static methods are actually the same thing. You still have a tight coupling between your classes and your singleton and singleton implementation uses a static member anyhow. I will say to choose whatever suits your style best.


I prefer to use singleton. an disadvantage of static is it always exist when app start, it will cost some memory from system even you not used this object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜