Last active
May 22, 2017 07:51
-
-
Save ZaeemSattar/ac1f086e21df8fc855b51538e1ec7d81 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Creational patterns: how you create objects. | |
Structural patterns: how you compose objects. | |
Behavioral patterns: how you coordinate object interactions. | |
Creational: | |
Builder | |
Dependency Injection | |
Singleton | |
Structural: | |
Adapter | |
Facade | |
Behavioral : | |
Command | |
Observer | |
Model View Controller | |
Model View ViewModel | |
//dagger 2 & dependency injection | |
is the most popular open-source dependency injection framework for Android and was developed in collaboration between Google and Square. You simply annotate a class with @Module, and populate it with @Provides methods such as the following: | |
@Module | |
public class AppModule { | |
@Provides SharedPreferences provideSharedPreferences(Application app) { | |
return app.getSharedPreferences("prefs", Context.MODE_PRIVATE); | |
} | |
} | |
The module above creates and configures all required objects. As an additional best-practice in larger apps, you could even create multiple modules separated by function. | |
Then, you make a Component interface to list your modules and the classes you’ll inject: | |
@Component(modules = AppModule.class) | |
interface AppComponent { | |
... | |
} | |
The component ties together where the dependencies are coming from (the modules), and where they are going to (the injection points). | |
Finally, you use the @Inject annotation to request the dependency wherever you need it: | |
@Inject SharedPreferences sharedPreferences; | |
As an example, you could use this approach in an Activity and then use local storage, without any need for the Activity to know how the SharedPreferences object came to be. | |
Admittedly this is a simplified overview, but you can read up on the Dagger documentation for more detailed implementation details. This pattern may seem complicated and “magical” at first, but its use can help simplify your activities and fragments. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment