Singletons have drawbacks. This is an old argument and I won’t get into it, but if you find static classes or Singletons are serving large portions of your app, here’s an alternative approach I’ve found success with. This is in directly violation of DI and I understand there are valid arguments against it, but at the same time for a complex app to properly DI you either have to decorate it to insensibility with something like Dagger, or have Builders for every instance of anything doing any work, or have constructors with way too many arguments, etc. While this isn’t specifically functional, the accessor is.

There are also arguments against storing any kind of information on the Application object – so far I’ve found these arguments a little weak, and are hinged on manual management (and common sense), but again, this post is not meant to start a discussion on the merits of using an Application subclass. If you’ve decided that’s a viable path for you, read on. If not, feel free to continue to @Inject 🙂

1. Provide a custom Application class for your app https://developer.android.com/reference/android/app/Application.html

2. Attach all your “singleton” classes (ImageLoader, DownloadService, Database connector, etc – anything lots of parts of your app need access to) as member instances on the Application subclass:

3. Provide a static getter to get the MyApplication instance from any context:

That’s it. Now you have control over state (instances not singletons), mockable properties, a functional getter, etc. I’m unaware of any behavioral drawback to this approach. Feel free to let me know if you agree or disagree.