android - AppContainer vs Singleton - 哪一个可以简化 Android 中的测试?
问题描述
我实际上是在探索 Android 中的依赖注入(DI)。在探索使手动DI 与自动DI相比变得困难的原因时,我尝试实现手动DI的Android 文档中给出的示例。
在我上面提到的文档中,提到了Singleton,它会使代码难以测试,因为测试将连接到同一个地方。
而且,为了克服这个问题,他们尝试使用AppContainer来全局访问对象。下面是他们提到的 AppContainer 类。
// Container of objects shared across the whole app
class AppContainer {
// Since you want to expose userRepository out of the container, you need to satisfy
// its dependencies as you did before
private val retrofit = Retrofit.Builder()
.baseUrl("https://example.com")
.build()
.create(LoginService::class.java)
private val remoteDataSource = UserRemoteDataSource(retrofit)
private val localDataSource = UserLocalDataSource()
// userRepository is not private; it'll be exposed
val userRepository = UserRepository(localDataSource, remoteDataSource)
}
AppContainer的实例在Application类中创建一次。并且,通过 Application 类,它在整个应用程序中公开UserRepository 。
来回答我的问题, AppContainer如何在像 Singleton 那样保存对象以在应用程序中共享的同时简化测试?
解决方案
推荐阅读
- android - 列表未添加到android中的arraylist
- ios - 显示 Invalid Binary Xcode 11 beta 6 的 iOS 应用
- typescript - 抑制打字稿编译中的 ERRNO 2 错误
- ionic-framework - 是否有任何离子代码可以使用 ionic 3 在蓝牙打印机上打印条码
- r - 从 mutate 中的符号创建列(整洁的评估)
- javascript - jQuery 不选择元素(Wordpress)
- java - 在 spring 和 eclipse 中演示微服务不起作用
- java - 可以在 BCrypt 中设置明文或将其转换为盐吗?
- angular - 如何在Angular中的函数内部http请求后返回blob url
- c# - C# 从大型文本文件中删除重复项