java - Android改造设计模式

标签 java android retrofit2

我正在使用 Retrofit 与我的 REST API 交互,想知道是否有人有任何设计建议。

我的应用有以下包:

  1. 模特
  2. 服务
  3. Activity
  4. 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/

相关文章:

java - 如何在 Jframe 中创建 JPanel?

java - 如何检查从 Google Place Search 获得的结果中是否存在 'rating' 字段?

java - Dagger + retrofit 。在运行时添加身份验证 header

android - 使用 Retrofit 时如何构建 API

android - Android 19 模拟器上的 API 调用 : isConnected failed: EHOSTUNREACH (No route to host)

java - 如何理解 - 访问变量时不需要出于任何其他原因进行锁定

java - AndroidX Work Library 正在取消操作,看似没有原因

java - Camel 没有捕捉到异常

Android SDK 和 AVD Manager 设置菜单在哪里?

android - 如何仅在android中获取用户创建日期