再看一遍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的作用、原理和啓示

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