再看一遍Retrofit

说起来Retrofit是Android App常用的轮子, 原理比较简单; 就是通过动态代理并获取函数注解, 从而方便实现http请求逻辑;

从架构角度, 我们能从Retrofit源码里学到什么呢?
1、深入理解动态代理的应用范围, 这是retrofit的核心逻辑;
2、声明各种注解表示不同的作用; 是不是感觉有点像枚举的作用?
3、retrofit不实现网络交互, 只是对Okhttp的封装搬运工;
4、对外只暴露一个类Retrofit, 迪米特法则;

Retrofit实例是线程安全的, 因为它用了ConcurrentHashMap并使用了synchronized代码块。

public final class Retrofit {
  private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();

  final okhttp3.Call.Factory callFactory;
  final HttpUrl baseUrl;
  final List<Converter.Factory> converterFactories;
  final List<CallAdapter.Factory> callAdapterFactories;
  final @Nullable Executor callbackExecutor;


 ServiceMethod<?> loadServiceMethod(Method method) {
    ServiceMethod<?> result = serviceMethodCache.get(method);
    //优先取缓存
    if (result != null) return result;
    //同步锁
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        result = ServiceMethod.parseAnnotations(this, method);
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

最近公司在做代码规范讨论和静态代码检查工作, 每次看这些开源代码都能学到些知识。

Retrofit代码量并不多, 看似不难, 但为什么是JakeWharton先写出来而不是你?
多学习、多思考、多实践;

参考:从架构角度看Retrofit的作用、原理和启示

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章