仿Retrofit代理模式实现多业务解耦

2017-10-16  本文已影响0人  vesselzhang

Retrofit最近是非常的火,相信大家都已经在非常麻溜的使用了,还没接触过的同学建议先移步retrofit官网
首先我们来看一下Retrofit的国际通用用法:

public class RetrofitSimple {
    private static DataServiceInterface serviceInterface;

    static {
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder().baseUrl("https://api.xxxxx.com/")
                .addConverterFactory(GsonConverterFactory.create());
        serviceInterface = retrofitBuilder.build().create(DataServiceInterface.class);
    }

    public static DataServiceInterface getService() {
        return serviceInterface;
    }
}

这里每个retrofit.create方法只放回DataServiceInterface对象,在大型项目中会有多个模块的存在,而每个模块都会有网络请求,这就会导致出现多个上述代码,不符合编程之美。

    private static <T> T initService(String baseUrl, Class<T> clazz) {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        OkHttpClient client = builder.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();

        return retrofit.create(clazz);
    }

上述代码即可根据传入的Service代码动态生成对应的网络请求管理类。这样我们就可以根据业务逻辑创建多个Service。当然我们可以提供一个公共的service管理类,方便各个模块调用。
完整代码如下:

public final class ApiClient {
    public static String baseUrl = "https://api.xxxxx.com/";
    public static AppService appService;
    public static ModuleAService moduleAService;
    public static ModuleBService moduleBService;

    public static ApiConfiguration configuration;

    public static void init(ApiConfiguration configuration){

        ApiClient.configuration = configuration;

        appService = initService(baseUrl, AppService.class);
        moduleAService = initService(baseUrl, ModuleAService.class);
        moduleBService = initService(baseUrl, ModuleBService.class);
    }

    private static <T> T initService(String baseUrl, Class<T> clazz) {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        OkHttpClient client = builder.build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(FastJsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();

        return retrofit.create(clazz);
    }
}

Over

上一篇下一篇

猜你喜欢

热点阅读