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,影响性能.
网友评论