动态代理模式的作用:实现了日志和业务的分开,也就是某个类只是要提供了某些业务。
动态代理另一个例子:
public class VectorProxy implements InvocationHandler {
private Object proxyObj;
public VectorProxy(Object obj){
this.proxyObj = obj;
}
public static Object factory(Object obj){
Class
classType = obj.getClass();
return Proxy.newProxyInstance(classType.getClassLoader(),classType.getInterfaces(),new VectorProxy(obj));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("before calling :"+method);
if(null != args){
for(Object o :args){
System.out.println(o);
}
}
Object object = method.invoke(proxyObj,args);
System.out.println("after calling :"+method);
return object;
}
public static void main(String[] args) {
List v = (List)factory(new Vector());
v.add("New");
v.add("York");
}
}
打印:
before calling :public abstract boolean java.util.List.add(java.lang.Object) New after calling :public abstract boolean java.util.List.add(java.lang.Object) before calling :public abstract boolean java.util.List.add(java.lang.Object) York after calling :public abstract boolean java.util.List.add(java.lang.Object)