Extending application or using singletion?

眉间皱痕 提交于 2019-12-22 20:28:48

问题


I have an android project where i have different objects that one or more of my activities need to acess now i was thinking of creating a subclass of Application however under the documentation of Application it states the following:

There is normally no need to subclass Application. In most situation, 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), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

My question is fairly simple is it best pratice to use a static singleton class to contain all of your objects ? or am i right to assume that extending application is a better option?


回答1:


To answer your question I would use a singleton container to access these objects, initialize that class with a context by application context (there are very big chances you will need a Context); but then you will see it's kind of hard to maintain these and the singleton container.

To solve this object graph issue, I would use some IoC: RoboJuice, AndroidAnnotations or Dagger are really cool and they provide much more. Each of them handles this issue different, but you don't have to worry about that.

I hope it helps!



来源:https://stackoverflow.com/questions/16972545/extending-application-or-using-singletion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!