android 中的 Dagger2 与应用程序 class

Dagger2 vs Application class in android

通过这个简单的例子

public class MyApp extends Application {
private static MyApp app;
private ImageDownloaderComponent imageDownloaderComponent; // dagger2

ImageDownloader imageDownloader;
@Override
public void onCreate() {
    super.onCreate();
    app = this;
    imageDownloaderComponent = DaggerImageDownloaderComponent.builder().imageDownloaderModule(new ImageDownloaderModule(this)).build();

    imageDownloader=new ImageDownloader(this);

}

public static MyApp app(){
    return app;
}

public ImageDownloaderComponent getImageDownloaderComponent(){
    return this.imageDownloaderComponent;
}
}

使用 Dagger2

public class MainActivity extends AppCompatActivity {
@Inject ImageDownloader downloader;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MyApp.app().getImageDownloaderComponent().inject(this);

    ImageView imageView = findViewById(R.id.main_image);
    downloader.toImageView(imageView, "https://..../fruits.png");
    } } 

没有匕首2

public class Main2Activity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ImageView imageView = findViewById(R.id.main_image);    
MyApp.app().imageDownloader.toImageView(imageView, "https://---/fruits.png");
 }
} 

这两种情况 activity 都工作正常。我的问题是为什么我们需要 dagger2 甚至由应用程序 class 执行相同的任务?其方式如何有效?我 google 它,除了那里的任何好处之外,我还很容易进行测试??在上面的例子中哪个 activity 是好的?为什么?

我们知道 Dagger 是依赖注入。

使匕首独一无二的简介:

好处:

  1. 如果我们像你给的那样在非常小的projects/tasks中使用匕首那么匕首就不会 deserve for that.It 用于中长应用程序会更有效率。因为它可以帮助我们避免在代码中创建不需要的对象。

  2. 我们可以使用dagger通过对象图复用对象

  3. 我们可以像这样分发依赖
    • 项目级别
    • 应用级别
    • 模块级别(如:主页、应用中的帐户)
  4. 我们可以定义自定义作用域,也有一些已经定义好的作用域,比如单例,匕首中有很好的概念,比如组件依赖 & 子组件.

  5. 可以注入Class,Object,Constructor。