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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值