Retrofit的设计模式 -- 享元模式

Retrofit中的享元模式

上次看到Retrofit中的动态代理模式,其中有段代码如下:

  public <T> T create(final Class<T> service) {
    Utils.validateServiceInterface(service);
    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, 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);
            }
            ServiceMethod serviceMethod = loadServiceMethod(method);
            OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }

其中用到的享元模式就是 loadServiceMethod这个函数:

ServiceMethod loadServiceMethod(Method method) {
    ServiceMethod result;
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        result = new ServiceMethod.Builder(this, method).build();
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

可以看到serviceMethodCache就是一个LinkedHashMap(拿数据顺序和存数据顺序一样的HashMap),这里用LinkedHashMap数据结构个人认为主要是为了存储以后可以快速提取的优势.

private final Map<Method, ServiceMethod> serviceMethodCache = new LinkedHashMap<>();

可以看到主要是从Method转到ServiceMethod,先从serviceMethodCache 缓存里面取,拿到就直接用,拿不到就new 新对象(Builder模式建立新对象)然后存入serviceMethodCache 缓存,这样就避免过多创建对象导致gc,影响性能.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容