Android改造设计模式

JB2*_*JB2 4 java android retrofit2

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

我的应用程序包含以下包:

  1. 楷模
  2. 服务
  3. 活动
  4. 片段

该服务包中包含用于改造的接口.例如:

public interface FooService {
    @FormUrlEncoded
    @POST("foo/do")
    @Headers("Content-Type: application/x-www-form-urlencoded; charset=UTF-8")
    Call<FooBar> do();
}
Run Code Online (Sandbox Code Playgroud)

模型包含......好吧,不同的模型.例如,FooBar.到目前为止一切都很好 - 就像Retrofit文档一样.

我创建了一个API类,它处理Retrofit构建逻辑(Retrofit retrofit = new Retrofit.Builder()等),并公开一个静态字段:retrofit.在我的活动中,我可以按如下方式执行我的请求:

FooService service = API.retrofit.create(FooService.class);
Call<FooBar> call = service.do();

try {
    retrofit2.Response response = call.execute();
    // ...do stuff...
} catch(IOException) {}
Run Code Online (Sandbox Code Playgroud)

随之而来的是我的问题:进一步抽象上述内容会更好吗?所以我不需要在任何地方重复上述内容?例如,类似于:

MyOtherFooService service = new  MyOtherFooService();
FooBar fooBar = service.do();
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?建议?

Ami*_*mir 11

我通常使用具有以下结构的单例模式:

首先定义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();
}
Run Code Online (Sandbox Code Playgroud)

然后将所有服务放入IService(在我的情况下IPlusService)

    public interface IPlusService {
    //@Headers( "Content-Type: application/json" ) in Post method may use this
    @GET("/api/category")
    Call<List<CategoryModel>> getAllCategory();
}
Run Code Online (Sandbox Code Playgroud)

然后在您的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);
        }
    });
Run Code Online (Sandbox Code Playgroud)