懒惰初始化与单身人士的单身人士带有刀柄注释
假设我想创建一个遵循Singleton模式的对象
。我可以通过以下方式做到这一点:
方法1:使用懒惰初始化
@Singleton
object RetrofitCreator {
val retrofitBuilder: Retrofit.Builder by lazy {
Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create())
.baseUrl("https://sample.com")
.build()
.create(ApiService::class.java)
}
}
方法2:带有刀柄注释的单例方法,
@Module
@InstallIn(ApplicationComponent::class)
object RetrofitCreator {
@Provides
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://sample.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
我显示的两种方法有什么区别?其中之一比另一个更好吗?如果是这样,哪种方法以及为什么?
Let's say I want to create an object
that follows the Singleton pattern. I can do it in the following ways:
Method 1: Singleton using Lazy Initialization
@Singleton
object RetrofitCreator {
val retrofitBuilder: Retrofit.Builder by lazy {
Retrofit.Builder()
.addConverterFactory(MoshiConverterFactory.create())
.baseUrl("https://sample.com")
.build()
.create(ApiService::class.java)
}
}
Method 2: Singleton with Hilt Annotations
@Module
@InstallIn(ApplicationComponent::class)
object RetrofitCreator {
@Provides
fun provideRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl("https://sample.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
What is the difference between the two methods I have shown? Is one of them better than the other? If so, which method and why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
依赖注射是非常不同的。比较使用单单鼠和懒惰和刀柄的比较就像将苹果与橙子进行比较。
什么是懒惰的初始化?
懒惰初始化是只有在应用程序中首次使用的对象时才能创建该对象时。如果从未使用过变量,它不会创建它以节省内存和提高性能。
什么是依赖注入?
不同的类通常取决于其他对象工作。像ViewModels一样,取决于存储库来获取数据(MVVM Arch)。初始化期间通过依赖关系的过程可能会很麻烦,尤其是在项目后期,如果您想更改存储库的实现。
依赖注入通过在幕后生成样板代码,以使您的生活更轻松,以便在需要的任何地方传递依赖项,而不是手动创建它。
在您的示例中,两者之间没有比较的问题。如果您在项目中加入匕首,则使用第二种方式。如果不是,那就第一个。
Dependency Injection is something very different. Comparing using Singletons with lazy and Hilt is like comparing apples with oranges.
What is Lazy Initialization?
Lazy Initialization is when you want to create an object only when it is first used in the application. If the variable is never used, it will not create it to save memory and improve performance.
What is Dependency Injection?
Different classes often depend on other objects to work. Like ViewModels depend on repositories in order to fetch data (MVVM arch). The process of passing dependencies during initialization can be troublesome, especially later in the project if you want to change the implementation of the repository.
Dependency Injection makes your life easier by generating the boilerplate code behind the scenes to pass in the dependencies wherever required instead of you manually creating it.
In your example, there is no question of comparison between the two. If you are including Dagger Hilt in your project, you use the second way. If you aren't, then the first.