dagger2 makes you love it: the end

http://android.jobbole.com/82705/

Preface

If you are not clear about the concept of dagger2 and the entire dependency injection framework, you can first understand my first two articles:

" Dagger2 makes you love it: basic dependency injection framework "
" Dagger2 makes you love it: key concepts and integration "

These two articles have also received praise and questions from many netizens. Thank you for your support. I probably summarized the following questions:

  • What are the benefits of dagger2?
  • How to use dagger2?

So I will combine these two points to explain this article. And there will be specific samples.

What are the benefits of dagger2?

Let's go straight to the topic:

Increase development efficiency and save repeated simple manual labor

First of all, the process of a new instance is a repetitive simple manual labor. Dagger2 can completely do the work of a new instance. Therefore, we focus our main energy on key business and increase development efficiency.

Save the method of writing a singleton, and you don't need to worry about whether the singleton method you write is thread-safe, whether the singleton you write is the lazy man mode or the hungry man mode. Because dagger2 can do these tasks.

Better management class instance

The ApplicationComponent in each app manages the global class instances of the entire app, and all global class instances are managed by ApplicationComponent, and their life cycle is the same as that of the app.

Each page corresponds to its own Component, and the page Component manages all the class instances that its own page depends on.

Because of Component, Module, the class instance structure of the entire app becomes very clear.

Decoupling

If dagger2 is not used, the new code of a class is very likely to be flooded in multiple classes of the app. If the constructor of the class changes, then these involved classes have to be modified. The design pattern advocates encapsulating the easily changeable parts .

After we used dagger2.

假如是通过用Inject注解标注的构造函数创建类实例,则即使构造函数变的天花乱坠,我们基本上都不需要修改任何代码。

假如是通过工厂模式Module创建类实例,Module其实就是把new类实例的代码封装起来,这样即使类的构造函数发生变化,只需要修改Module即可。

有个网友问过一个这样的问题,Module的构造函数也会发生变化,发生变化后,相应的new Module的类也发生变化,这就没有达到解耦的效果。首先解耦不是说让类之间或模块之间真的一点关系都没有了,解耦达到的目的是让一个类或一个模块对与自己有关联的类或模块的影响降到最低,不是说这种影响就完全没有了,这是不可能的。

解耦还有个好处,就是方便测试,若需要替换为网络测试类,只需要修改相应的Module即可。

项目中使用dagger2注意点

具体的代码就不讲了,dagger2 sample地址,大家自行下载。这里重点说下dagger2对目标类进行依赖注入的过程,现在假设要初始化目标类中的其中一个依赖类的实例,那具体步骤就在下面:

以上是dagger2进行的一次依赖注入的步骤,其实这个步骤是一个递归的过程,并且在查找类的实例的过程中Module的级别要高于Inject,这概念在上一篇讲过。

下面在说下注意的几点

  • 一个app必须要有一个Component(名字可以是ApplicationComponent)用来管理app的整个全局类实例
  • 多个页面可以共享一个Component
  • 不是说Component就一定要对应一个或多个Module,Component也可以不包含Module
  • 自定义Scope注解最好使用上,虽然不使用也是可以让项目运行起来的,但是加上好处多多。

总结

好了关于dagger2的所有的概念知识点到此终于结束了,希望能帮助大家,与大家共勉,有问题可以随时与我沟通。


Guess you like

Origin blog.csdn.net/kerwinJu/article/details/52832717