打破Dagger中的循环依赖

时间:2015-07-23 01:50:48

标签: dagger cyclic-dependency

我对匕首很新 - 我甚至不知道它是否适用于我的应用程序

我有一个搜索页面,可以返回有关特定名人的最新消息。

我写了一个测试来验证当我们搜索热门名人时,结果会显示在页面上。

pagesearchField,在构造函数中需要page,因此我用于测试的网络驱动程序可以选择它。

名人搜索页面测试

public class CelebritySearchPageTest {
    @Test
    public void testSearchResultsForKevinBaconVerifyHisPopularity() {
        CelebritySearchPage searchPage = new CelebritySearchPage();
        searchPage.searchFor("Kevin Bacon");
        Assert.assertTrue(searchPage.getNumberOfResults() > 9999999, "Verify that Kevin Bacon is still relevant");
    }
}

名人搜索页面

public class CelebritySearchPage extends Page {
    @Inject
    @Named("search field")
    TextField searchField;

    public void searchFor(String text) {
        searchField.setText(text);
        // ...
    }

    public int getNumberOfResults() {
        // ...
    }
}

名人搜索页面模块

@Module(injects = CelebritySearchPage.class)
public class CelebritySearchPageModule {
    @Provides
    @Named("search field")
    public TextField provideSearchField() {
        return new TextField(/* How do I get the page? */, "#searchField");
    }
}

网页

public abstract class Page {
    // ...
}

文字字段

public class TextField {
    protected Page page;
    protected String selector;

    public TextField(Page page, String selector) {
        this.page = page;
        this.selector = selector;
    }

    public void setText(String text) {
        // ...
    }
}

问题在于page需要searchField,但searchField需要page。我如何克服这种循环依赖?

我无法初始化CelebritySearchPage中的searchField

1 个答案:

答案 0 :(得分:1)

考虑一下:

CelebritySearchPage

public class CelebritySearchPage extends Page {
    private final Lazy<TextField> searchField;
// always prefer constructor injection
// avoid @Named if possible, since the compiler cannot check the string
    @Inject
    CelebritySearchPage(@Named("search field") Lazy<TextField> searchField) {
        this.searchField = searchField; 
    }
}

文字字段

public class TextField {
    protected final Lazy<Page> page;
    protected final String selector;

    @Inject TextField(Lazy<Page> page, String selector) {
        this.page = page;
        this.selector = selector;
    }

/*
Lazy::get()
Return the underlying value, computing the value if necessary. All calls to      the same Lazy instance will return the same result.
*/
}

我想一个懒人也应该足够了。