我注入(inject)
viewModels
、存储库
、 fragment
、Utils
和.. .但是使用依赖注入(inject)
Koin
或Dagger-hilt<来
?注入(inject)
通用class
是个好方法吗?/
假设我们要在fragment
中使用StringBuilder()
类
第一种方法:
我们可以注入(inject)
它
val otherModule= module {
single { StringBuilder() }
}
并在fragment
中使用它,如下所示:
class Fragment : BaseFragment(){
private val mPassword : StringBuilder by inject()
}
第二种方法:
我们可以创建新
实例
而无需注入(inject)
class Fragment : BaseFragment(){
private var mPassword = StringBuilder()
}
我的问题是第一种方法对我们来说是常见的方法吗?
最佳答案
我想说这要看情况。 Di 背后的主要目标/概念是实现 S.O.L.I.D 的第一原则,或者如 freecodecamp.org 所说:
It is the fifth principle of S.O.L.I.D — the five basic principles of object-oriented programming and design by Uncle Bob — which states that a class should depend on abstraction and not upon concretions (in simple terms, hard-coded).
According to the principles, a class should concentrate on fulfilling its responsibilities and not on creating objects that it requires to fulfill those responsibilities. And that’s where dependency injection comes into play: it provides the class with the required objects.
提供了另一个很好的答案here ,因为已经讨论了何时不使用依赖注入(inject)。
现在我的观点是:如果可能的话,尝试注入(inject)那些必须经常使用的依赖项,如果可能的话,通过构造函数注入(inject)来注入(inject)它们。这样,您可以轻松查看您的类使用了哪些依赖项。尽量不要注入(inject)使用过一次的类或者通用语言类。
关于android - 通过依赖注入(inject)来注入(inject)公共(public)类是个好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64291385/