類似 Scala 的 Trait,第一是函數式 Lambda 基本是基於 default 實現的。第二就是類似裝飾功能,增加方法,同時不用擔心菱形繼承。
```java
/**
* A common helper interface for easy handle retrofit request
* Inspired by scala's Trait design
*/
public interface RetrofitCallAdaptor {
/**
* Helper method to generate a real rest network request, use it as you wish
*
* @
param retrofitCall the retrofit {@link Call} interface instance
* @
param <T> the implicit type of response
* @
return the converted response if request success, otherwise the {@link RetrofitRequestFailedException} would be thrown
*/
default <T> T execute(Call<T> retrofitCall) {
try {
Response<T> response = retrofitCall.execute();
if (response.isSuccessful()) {
return response.body();
}
ResponseBody errorBody = response.errorBody();
// Null would be present only if the request is successful. Add null check only to make sonar happy
throw new RetrofitRequestFailedException(errorBody == null ? "请求失败" : errorBody.string(), ErrorCode.NET_REQUEST_ERROR);
} catch (IOException e) {
throw new RetrofitRequestFailedException(e, ErrorCode.NET_REQUEST_SUSPEND);
}
}
}
```
比如我有一個方法,很多類都需要用,他們都有自己的特殊父類,不好擴展出一個抽象類。我又不想寫一個 Utils,那麼用接口就是最方便的。