动态代理设计模式的最大特点是可以同时为若干个功能相近的类提供统一的代理支持,这就必须要定义一个公共的代理类,在java中针对此动态代理提供了一个公共的标准接口InvocationHandler
public interface InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
proxy:代理对象
method: 要执行的目标类方法
args: 执行方法所需要的参数
除了提供统一的代理操作类外,还需要在类运行中依据被代理类所实现的父接口动态的创建一个临时的代理对象,而这一操作就可以通过Proxy类来实现;
创建代理对象:
public static Object newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)
package com.cn;
public interface Imessage {
public void send();
}
package com.cn;
public class MessageReal implements Imessage {
@Override
public void send() {
System.out.println("[发送消息]===================");
}
}
package com.cn;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MLDNProxy implements InvocationHandler {
private Object target;
public Object bind(Object target){
this.target=target;
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(),this);
}
public boolean connect(){
System.out.println("[消息代理] 进行消息发送通道的链接");
return true;
}
public void close(){
System.out.println("[消息代理] 关闭消息通道");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object returnData=null;
if (this.connect()){
returnData = method.invoke(this.target,args);
this.close();
}
return returnData;
}
}
package com.cn;
public class JavaReflectDemo {
public static void main(String[] args) {
Imessage imessage =(Imessage) new MLDNProxy().bind(new MessageReal());
imessage.send();
}
利用InvocationHandler接口定义了一个代理类,该代理类不会与任何接口有耦合关联,并且所以的代理对象都是通过Proxy根据真实对象的结构动态创建而来,由于动态代理类具有通用性的特点,所以每当用户调用方法时都会执行代理类中的invoke方法,该方法将通过反射的形式调用真实的方法.