Using Dependency Injection with Roboguice?

2019-01-13 00:26发布

问题:

I'm working on an Android project and I would like to know any recommendations about what's a good architecture to build an android application.

I want to use dependency injection using Roboguice and I've been reading about MVVM pattern or MVC pattern (Android MVVM Design Pattern Examples).

Also I know that roboguice have a pretty cool Context-Based Event's raising and handling feature that could be very testable as the code is decoupled.

Any recommendations on a working design pattern? a testable and scalable architecture you have worked with or developed?

回答1:

The Android platform provides a common set of design patterns, and with the limited hardware resources you get compared to Web-apps it is still often best to stick with using these directly in production code. There are other frameworks that sort of "wrap" the base platform; these are worth looking into if you have a specific purpose (or perhaps for prototyping/experimenting), but for the best level of support you are generally best sticking with the standard components.

This is a great resource when working on UI solutions: http://www.androidpatterns.com/

Specifically for DI: There is a Spring framework for Android, I've had a play with it and it looks quite promising. You've already mentioned Roboguice as another alternative to this. However, to avoid performance and library overhead, I still find the easiest approach is to write a simple reflection-based class that registers and injects dependencies within my own code. Similar to this approach, except I usually move the injection code into a separate singleton and reference it from there.

In my experience most of the third-party offerings are not yet mature enough to rely on right now, and don't really give you much on top of what the base platform provides. They are constantly progressing, however, so be sure to experiment with the big names from time-to-time.