如何使用拖动器 2 创建一个带有模拟数据的单例类?

我想知道是否可以使用模拟数据和拖动器创建一个单例


我知道不使用拖动器 2 的标准代码


public class Singleton {

    private Singleton() { }


    private static class SingletonHolder {

        private static final Singleton INSTANCE = new Singleton();

    }


    public static Singleton getInstance() {

        return SingletonHolder.INSTANCE;

    }


    public String getFoo() {

        return "bar";

    }

}

在这里,我知道将带有数据的数组列表放在哪里进行模拟,但是如何用匕首做到这一点,用于将 ArrayList 与数据一起放置的设置函数或类似函数在哪里,以及如何调用。


慕娘9325324
浏览 89回答 1
1回答

Smart猫小萌

您只需要在其中一个模块中添加一个方法并使用 @Singleton 注释对其进行注释。例如:@Modulepublic class MyModule {&nbsp; &nbsp; @Provides&nbsp; &nbsp; @Singleton&nbsp; &nbsp; MockData provideMockData() {&nbsp; &nbsp; &nbsp; &nbsp;return new MockData(Arrays.asList("A", "B", "C"));&nbsp; &nbsp; }&nbsp; &nbsp; @Provides&nbsp; &nbsp; OtherClass provideOtherClass(MockData mockData) {&nbsp; &nbsp; &nbsp; &nbsp;return new OtherClass(mockData);&nbsp; &nbsp; }}public class MockData {&nbsp; &nbsp; private List<String> list;&nbsp; &nbsp; public MockData(List<String> list){&nbsp; &nbsp; &nbsp; &nbsp; this.list = list;&nbsp; &nbsp; }&nbsp; &nbsp; public List<String> getList() {&nbsp; &nbsp; &nbsp; &nbsp; return list;&nbsp; &nbsp; }}检查https://google.github.io/dagger/users-guide.html中的“单例和作用域绑定”部分
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java