代理模式(Proxy Pattern) :给某一个对象提供一个代 理,并由代理对象控制对原对象的引用。代理模式的英 文叫做Proxy或Surrogate,它是一种对象结构型模式。
接口类
interface ProxyInterface{
void testProxy();
}
实现类
static class ProxyImpl implements ProxyInterface{
@Override
public void testProxy() {
System.out.println("我执行了");
}
}
调用示例
public static void main(String[] args){
final Class cla = ProxyInterface.class;
ProxyInterface proxy = (ProxyInterface) Proxy.newProxyInstance(cla.getClassLoader(), new Class[]{cla}, new InvocationHandler() {
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
return method.invoke(new ProxyImpl(),objects);
}
});
proxy.testProxy();
}
以Retrofit动态代理接口类方法示例
public <T> T create(final Class<T> service) {
//接口验证
Utils.validateServiceInterface(service);
//是否提前验证
if (validateEagerly) {
// 给接口中每个方法的注解进行解析并得到一个ServiceMethod对象,以Method为键将该对象存入LinkedHashMap集合中
// 如果不是提前验证则进行动态解析对应方法得到一个ServiceMethod对象,最后存入到LinkedHashMap集合中,类似延迟加载(默认)
eagerlyValidateMethods(service);
}
//通过动态代理创建接口的实例,为了获取接口方法上的所有注解
return (T) Proxy.newProxyInstance(
service.getClassLoader(),//动态生成接口实现类
new Class<?>[]{service},//动态创建实例
//代理类的具体实现交给InvocationHandler处理
new InvocationHandler() {
private final Platform platform = Platform.get();
//接口方法的调用也即通过调用InvocationHandler对象的invoke()来完成指定的功能
/**
* 所有接口方法的调用都会集中到这里进行处理
* @param proxy 接口对象
* @param method 调用的接口方法
* @param args 接口方法参数
*/
@Override
public Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
//Android平台下不处理
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
//一个ServiceMethod对应一个接口方法
ServiceMethod<Object, Object> serviceMethod = (ServiceMethod<Object, Object>) loadServiceMethod(method);
//创建OkHttpCall对象
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
//调用callAdapter进行请求适配,如Call<R>到Observable<R>
return serviceMethod.adapt(okHttpCall);
}
});
}