public class Application {
public static void main(String[] args) throws Exception {
IMessage message = new MessageProxy(new MessageReal());
message.send();
}
}
interface IMessage {
void send();
}
class MessageReal implements IMessage {
@Override
public void send() {
System.out.println("[SEND] Hello World!");
}
}
class MessageProxy implements IMessage {
private IMessage message;
public MessageProxy(IMessage message) {
this.message = message;
}
@Override
public void send() {
if (this.connect()) {
this.message.send();
this.close();
}
}
public boolean connect() {
System.out.println("[INFO] open connection...");
return true;
}
public void close() {
System.out.println("[INFO] close connection.");
}
}
通过静态代理的缺陷可以发现,最好的做法是为所有功能一直的业务操作接口提供统一的代理处理操作,而这就要通过动态代理来实现,但是在动态代理的过程中需要考虑到如下的一些问题:
public interface InvocationHandler {
/**
* 代理方法调用,代理主体类里面执行的方法最终都是此方法
* @param proxy 要代理的对象
* @param method 要执行的接口方法
* @param args 接口方法传递的参数
* @return 某个方法的返回值
* @throws Throwable 在调用过程中产生的错误
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
public class Application {
public static void main(String[] args) throws Exception {
IMessage message = (IMessage) new DynamicProxy().bind(new MessageReal());
message.send();
}
}
class DynamicProxy 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("[INFO] open connection...");
return true;
}
public void close() {
System.out.println("[INFO] close connection.");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("[EXEC] " + method);
Object result = null;
if (this.connect()) {
method.invoke(this.target, args);
this.close();
}
return result;
}
}
interface IMessage {
void send();
}
class MessageReal implements IMessage {
@Override
public void send() {
System.out.println("[SEND] Hello World!");
}
}