Retrofit2源码学习之Retrofit

综述

Retrofit采用Builder模式构建


Retrofit2源码学习之Retrofit_第1张图片
类图 来源[第一篇:Retrofit主要类UML图](http://www.cnblogs.com/wlrhnh/p/5466928.html)

源码研究

Retrofit类的源码本身比较简单,简单分析下build()create()两个主要方法

build()

build是构建一个Retrofit实例的方法

public Retrofit build() {
      //baseUrl判空处理
      if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
      }
      //加载Call,可以用client(OkHttpClient client)替换默认Call
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }
    
      Executor callbackExecutor = this.callbackExecutor;
      if (callbackExecutor == null) {
        //默认callbackExecutor在Platform中实现 
        //Android对应的就是MainThreadExecutor
        callbackExecutor = platform.defaultCallbackExecutor();
      }

      // Make a defensive copy of the adapters and add the default Call adapter.
      List adapterFactories = new ArrayList<>(this.adapterFactories);
      //添加默认的CallAdapter
      //Android平台默认ExecutorCallAdapterFactory   
      adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

      // Make a defensive copy of the converters.
      //添加用户自定义Converter.Factory
      List converterFactories = new ArrayList<>(this.converterFactories);
      
      return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
          callbackExecutor, validateEagerly);
    }

create()

create用于创建用户定义的ApiService动态代理对象

  public  T create(final Class service) {
    //判断是否合法的service
    Utils.validateServiceInterface(service);
    //是否在调用ApiService具体方法前提前创建ServiceMethod
    //一般用于在ApiService调用方法时不需要传递参数的Service,默认为false
    if (validateEagerly) {
      eagerlyValidateMethods(service);
    }
    //返回动态代理对象
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[] { service },
        new InvocationHandler() {

            private final Platform platform = Platform.get();
          @Override
          public Object invoke(Object proxy, Method method, @Nullable Object[] args)throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            //将service中的注释适配成URL组件
            ServiceMethod serviceMethod =
                (ServiceMethod) loadServiceMethod(method);
            //用serviceMethod 创建转化OKHttpCall
            OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
            //将OkHttpCall转化成最终的Call,默认为ExecutorCallbackCall(添加回调执行器)
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }
 
 

简单使用

        OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://bbs.csdn.net").client(okHttpClient).build();
        ProdectService prodectService = retrofit.create(ProdectService.class);
        prodectService.getopics("390044033").enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
            }

            @Override
            public void onFailure(Call call, Throwable throwable) {
            }
        });

扩展

代理(Proxy)模式

代理模式就是通过为对象建立一个占位符(new,newInstance,clone),用于管理对目标对象的访问,具体可以查看《Java设计模式》代理模式,动态代理

你可能感兴趣的:(Retrofit2源码学习之Retrofit)