我正在学习使用 Hilt 和 Dagger 进行依赖注入,我想知道...当使用 Singleton 模式创建类时,我应该使用真正的 Singleton 还是 Hilt 注释?我在互联网上搜索,但找不到显示差异的结论性解决方案,而且当我单击从 Hilt 打开生成的文件时,它看起来不像单例,它是“threadissuesproof”吗?
“真正的单例”,像这样:
class SongController private constructor() {
companion object {
@Volatile
private var INSTANCE: SongController? = null
fun getInstance(): SongController {
synchronized(this) {
var instance = INSTANCE
if (instance == null) {
instance = SongController()
INSTANCE = instance
}
return instance
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者 Hilt 的 @Singleton 注释?
@Singleton
class SongController @Inject constructor() {}
Run Code Online (Sandbox Code Playgroud)
使用注释有什么好处吗?最好、最安全的选择仍然是 getInstace() ->synchronized() 块?
在这种情况下我应该使用哪一个?
我不明白的最重要的问题是,注释的行为方式是否相同?