简体   繁体   English

具有惰性初始化的单例与具有 Hilt 注释的单例

[英]Singletons with lazy initialization vs singletons with Hilt annotations

Let's say I want to create an object that follows the Singleton pattern.假设我想创建一个遵循object模式的 object。 I can do it in the following ways:我可以通过以下方式做到这一点:

Method 1: Singleton using Lazy Initialization方法一:Singleton 使用 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方法二:Singleton 带 Hilt 注解

@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?如果是这样,哪种方法以及为什么?

Dependency Injection is something very different.依赖注入是非常不同的东西。 Comparing using Singletons with lazy and Hilt is like comparing apples with oranges.将 Singletons 与 lazy 和 Hilt 进行比较就像将苹果与橙子进行比较。

What is Lazy Initialization?什么是惰性初始化?

Lazy Initialization is when you want to create an object only when it is first used in the application. Lazy Initialization 是当你想要创建一个 object 只有当它第一次在应用程序中使用时。 If the variable is never used, it will not create it to save memory and improve performance.如果从未使用过该变量,则不会创建它以保存 memory 并提高性能。

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).就像 ViewModels 依赖于存储库来获取数据(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.如果您在项目中包含 Dagger Hilt,则使用第二种方式。 If you aren't, then the first.如果你不是,那么第一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM