Dagger2 vs工厂容器在android中依赖注入。哪个更好?

时间:2017-05-11 23:03:49

标签: android dependency-injection dagger-2

我正在辩论,如果我的团队更好地学习匕首而不仅仅是使用单件容器 这将提供依赖性。这就是在过去的日子里如何做到的。我是 专门处理android,这是我在网上找到的一个使用工厂容器的例子 依赖注入:

公共类容器{

private static Container instance;
private FavoriteAdder favoriteAdder;
private FavoriteRepo favoriteRepo;
private FavoritesGetter favoritesGetter;
private FavoriteRemover favoritesRemover;

private Container() {}

public static Container getInstance() {
    if (instance == null) {
        instance = new Container();
    }
    return instance;
}

public FavoriteAdder getFavoriteAdder() {
    if (favoriteAdder == null) {
        favoriteAdder = new FavoriteAdder(getFavoriteRepo());
    }
    return favoriteAdder;
}

public FavoritesGetter getFavoritesGetter() {
    if (favoritesGetter == null) {
        favoritesGetter = new FavoritesGetter(getFavoriteRepo());
    }
    return favoritesGetter;
}

public FavoriteRemover getFavoritesRemover() {
    if (favoritesRemover == null) {
        favoritesRemover = new FavoriteRemover(getFavoriteRepo());
    }
    return favoritesRemover;
}

public FavoriteRepo getFavoriteRepo() {
    if (favoriteRepo == null) {
        CachingFavoriteRepo inMemoryRepo = new InMemoryFavoriteRepo();
        FavoriteRepo remoteRepo = new SlowFavoriteRepoWrapper(new MockRemoteFavoriteRepo(), 1000);
        favoriteRepo = new FavoriteReadThroughCache(inMemoryRepo, remoteRepo);
    }
    return favoriteRepo;
}

}

然后在我们可以执行此操作的活动中使用它:

public class FavoriteActivity extends ActionBarActivity {


    private FavoriteAdder favoriteAdder = Container.getInstance().getFavoriteAdder();
    private FavoritesGetter favoritesGetter = Container.getInstance().getFavoritesGetter();
    private FavoriteRemover favoritesRemover = Container.getInstance().getFavoritesRemover();

    private FavoriteCrudPresenter presenter;

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

            presenter = new FavoriteCrudPresenter(favoriteAdder, favoritesGetter, favoritesRemover, Schedulers.io(), AndroidSchedulers.mainThread(), backgroundExecutor, foregroundExecutor);
//...

}}

使用匕首似乎更容易,我想知道匕首在这方面有什么好处? 为什么我们甚至打扰匕首我想它更容易让匕首中的单身人士成为一种情景。

0 个答案:

没有答案