我正在使用 Retrofit 与我的 REST API 交互,想知道是否有人有任何设计建议。
我的应用有以下包:
- 模特
- 服务
- Activity
- fragment
services 包包含 Retrofit 的接口(interface)。例如:
public interface FooService {
@FormUrlEncoded
@POST("foo/do")
@Headers("Content-Type: application/x-www-form-urlencoded; charset=UTF-8")
Call<FooBar> do();
}
模型包含……好吧,不同的模型。例如,FooBar。到目前为止一切顺利 - 正如 Retrofit 文档所述。
我创建了一个 API 类,它处理 Retrofit 构建逻辑(Retrofit retrofit = new Retrofit.Builder()
等),并公开一个静态字段:retrofit。然后在我的 Activity 中我可以按如下方式执行我的请求:
FooService service = API.retrofit.create(FooService.class);
Call<FooBar> call = service.do();
try {
retrofit2.Response response = call.execute();
// ...do stuff...
} catch(IOException) {}
随之而来的是我的问题:进一步抽象上述内容会更好吗?这样我就不需要到处重复上面的内容了?例如,像这样的东西:
MyOtherFooService service = new MyOtherFooService();
FooBar fooBar = service.do();
有什么想法吗?推荐?
最佳答案
我通常使用具有以下结构的单例模式:
首先像下面这样定义ServiceHelper
:
public class ServiceHelper {
private static final String ENDPOINT = "http://test.com";
private static OkHttpClient httpClient = new OkHttpClient();
private static ServiceHelper instance = new ServiceHelper();
private IPlusService service;
private ServiceHelper() {
Retrofit retrofit = createAdapter().build();
service = retrofit.create(IPlusService.class);
}
public static ServiceHelper getInstance() {
return instance;
}
private Retrofit.Builder createAdapter() {
httpClient.setReadTimeout(60, TimeUnit.SECONDS);
httpClient.setConnectTimeout(60, TimeUnit.SECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.interceptors().add(interceptor);
return new Retrofit.Builder()
.baseUrl(ENDPOINT)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create());
}
public Call<List<CategoryModel>> getAllCategory() {
return service.getAllCategory();
}
然后将所有服务放入IService
(在我的例子中是IPlusService
)
public interface IPlusService {
//@Headers( "Content-Type: application/json" ) in Post method may use this
@GET("/api/category")
Call<List<CategoryModel>> getAllCategory();
}
然后在您的 Activity/fragment 中调用您的单例:
ServiceHelper.getInstance().getAllCategory().enqueue(new Callback<List<CategoryModel>>() {
@Override
public void onResponse(Response<List<CategoryModel>> response, Retrofit retrofit) {
processResponse(response);
}
@Override
public void onFailure(Throwable t) {
processResponse(null);
}
});
关于java - Android改造设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36960627/