创建 Retrofit 服务 class Kotlin

Create Retrofit service class Kotlin

创建改造实例的最合适方法是什么?(不一定在下面的 3 个选项之间) 这3种方式有什么区别?

选项 1

object BuffApi {
    val retrofitService : BuffApiService by lazy {
        retrofit.create(BuffApiService::class.java)
    }
}

选项 2

object BuffApi {
    val retrofitService2: BuffApiService = retrofit.create(BuffApiService::class.java)
}

选项 3

class BuffApi {
    val retrofitService: BuffApiService = retrofit.create(BuffApiService::class.java)
}

如果您有可能不调用 retrofitService ,或者不经常调用,最好使用选项 1 - val retrofitService : BuffApiService by lazy { 因为您的程序不会初始化变量 retrofitService 直到您访问或调用它以减少内存使用量。

在另一种情况下 Option_2 会有所帮助,因为它是静态的,您不必在每次要访问它时都创建一个新对象,而且使用单个服务实例也是一种很好的做法,例如(改造存储库)类。

Option_2和Option_3的字节码生成几乎相同:40和64行:但是对于Option_1它是大约146行