【发布时间】:2020-08-26 23:58:57
【问题描述】:
我正在努力将这个改造类翻译成 Kotlin。它基本上是一个作为客户端工作的单例,我不确定我的 Kotlin 实现。 UserAPI 和 ProfileAPI 只是接口。
public class RetrofitService {
private static final String BASE_URL = "https://test.api.com/";
private ProfileAPI profileAPI;
private UserAPI userAPI;
private static RetrofitService INSTANCE;
/**
* Method that returns the instance
* @return
*/
public static RetrofitService getInstance() {
if (INSTANCE == null) {
INSTANCE = new RetrofitService();
}
return INSTANCE;
}
private RetrofitService() {
Retrofit mRetrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build();
profileAPI = mRetrofit.create(ProfileAPI.class);
UserAPI = mRetrofit.create(UserAPI.class);
}
/**
* Method that returns the API
* @return
*/
public ProfileAPI getProfileApi() {
return profileAPI;
}
/**
* Method that returns the API
* @return
*/
public UserAPI getUserApi() {
return userAPI;
}
}
这是我的 Kotlin 实现。据我了解,在实例化类时,将首先执行 init 块。
class RetrofitService private constructor() {
/**
* Method that returns the API
* @return
*/
private val profileApi: ProfileAPI
private val userAPI: UserAPI
companion object {
private const val BASE_URL = "https://test.api.com/"
private var INSTANCE: RetrofitService? = null
/**
* Method that returns the instance
* @return
*/
fun getInstance(): RetrofitService? {
if (INSTANCE == null) {
INSTANCE = RetrofitService()
}
return INSTANCE
}
}
init {
val mRetrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build()
profileApi = mRetrofit.create(ProfileAPI::class.java)
UserAPI = mRetrofit.create(UserAPI::class.java)
}
}
但是有些事情告诉我这不是正确的方法,或者可以做得更好。这里有什么可以改进的吗?
更新!!!
基于 cmets 和回答我现在有了这个实现
object RetrofitService {
private const val BASE_URL = "https://test.api.com"
private fun retrofitService(): Retrofit {
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(BASE_URL)
.build()
}
val profileApi: ProfileAPI by lazy {
retrofitService().create(ProfileAPI::class.java)
}
val userApi: UserAPI by lazy {
retrofitService().create(UserAPI::class.java)
}
}
那我就这样用了
RetrofitService.profileApi
这样可以吗?
【问题讨论】:
-
RetrofitService可以完全是一个对象。那么就不需要私有构造函数和init块了。
标签: java android kotlin singleton retrofit2