Kotlin,减少重复的代码

我的每个API服务接口类都创建了静态方法,

interface AuthApiService { @FormUrlEncoded @POST("api/auth/login") fun postLogin(@Field("username") username: String, @Field("password") password: String): io.reactivex.Observable companion object Factory { fun create(): AuthApiService { val gson = GsonBuilder().setLenient().create() val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("http:192.168.24.188:8080") .build() return retrofit.create(AuthApiService::class.java) } } } interface BBBApiService { companion object Factory { fun create(): BBBApiService { val gson = GsonBuilder().setLenient().create() val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("http:192.168.24.188:8080") .build() return retrofit.create(BBBApiService::class.java) } } } 

但是,我只想定义create()方法一次。

所以我做了ApiFactory类,

 interface ApiFactory { companion object { inline fun createRetrofit(): T { val gson = GsonBuilder().setLenient().create() val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("http://192.168.24.188:8080") .build() return retrofit.create(T::class.java) } } } interface AuthApiService { @FormUrlEncoded @POST("api/auth/login") fun postLogin(@Field("username") username: String, @Field("password") password: String): io.reactivex.Observable companion object Factory { fun create(): AuthApiService { return ApiFactory.createRetrofit() } } 

但是,我仍然需要在AuthApiService中定义create()方法。

有没有什么办法将ApiFactory类实现到SubApi类,以便我不必在每个子类中定义create方法?

一个简单的解决方案就是直接调用ApiFactory的函数:

 val authApiService = ApiFactory.createRetrofit() 

但是如果你想能够调用AuthApiService.create() ,那么你可以定义一个标记接口,比如说ApiFactoryClient ,并用它标记一个空的companion object

 interface ApiFactoryClient interface AuthApiService { /* ... */ companion object : ApiFactoryClient } 

然后创建一个与ApiFactoryClient一起使用的扩展函数:

 inline fun  ApiFactoryClient.create(): T = ApiFactory.createRetrofit() 

用法是:

 val authApiService = AuthApiService.create() 

你可以像这样修改你的ApiFactory

 interface ApiFactory { companion object { inline fun createRetrofit(klass: KClass): T { val gson = GsonBuilder().setLenient().create() val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl("http://192.168.24.188:8080") .build() return retrofit.create(klass.java) } } } 

然后用它来创建不同的服务实例:

 val authApiService = ApiFactory.createRetrofit(AuthApiService::class)