代理是基本的设计模式之一,它是为了提供额外的或不同的操作,而插入的用来代替“实际”角色的对象。这些操作通常涉及与实际对象的通信,因此代理充当着中间人的角色。
代码理解:
接口:
package com.proxy;
public interface Subject {
public void request();
}
实现:
package com.proxy;
public class RealSubject implements Subject {
public RealSubject() {
}
public void request() {
System.out.println("this is realSubject request()"+"方法");
}
}
InvocationHandler:
package com.proxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class ProxySubject implements InvocationHandler {
private Subject obj = null;
public ProxySubject() {
}
public ProxySubject(Subject obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("处理前");
method.invoke(obj, args);
System.out.println("处理后");
return null;
}
}
测试:
package com.proxy.test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import org.junit.Test;
import com.proxy.ProxySubject;
import com.proxy.RealSubject;
import com.proxy.Subject;
public class TestProxy {
@Test
public void test()
{
RealSubject realSubject = new RealSubject();
Class<?> cla = realSubject.getClass();
InvocationHandler handler = new ProxySubject(realSubject);
Subject subject = (Subject) Proxy.newProxyInstance(cla.getClassLoader(), cla.getInterfaces(), handler);
subject.request();
}
}
结果:
处理前
this is realSubject request()方法
处理后