java代理模式探索
代理是为了控制对被代理人的访问,代理关系常见经纪人和演员之间,双方的职责解耦。
场景一:静态代理
public interface Performance {
public void sing(String name);
}
public class Actor implements Performance{
@Override
public void sing(String name) {
System.out.println(name + "大河向东流!");
}
}
public class Agent implements Performance {
private Performance actor;
public Agent() {
actor = new Actor();
}
@Override
public void sing(String name) {
before();
actor.sing(name);
after();
}
private void before() {
System.out.println("Before");
}
private void after() {
System.out.println("After");
}
public static void main(String[] args) {
Performance agent = new Agent();
agent.sing("水浒");
}
}
场景二:JDK动态代理
public class Agent implements InvocationHandler {
private Object object;
public Agent(Object object) {
this.object = object;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Agent before doSth");
method.invoke(object, args);
System.out.println("Agent after doSth");
return null;
}
}
public class Client {
public static void main(String[] args) {
Performance actor = new Actor();
Performance actress = new Actress();
InvocationHandler handler = new Agent(actor);
Performance proxy = (Performance) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
actor.getClass().getInterfaces(), handler);
System.out.println(proxy.getClass().getName());
proxy.sing("水浒");
handler = new Agent(actress);
proxy = (Performance) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
actress.getClass().getInterfaces(), handler);
System.out.println(proxy.getClass().getName());
proxy.sing("美丽的祖国");
}
}
其它三个类同例一。
场景三:CGLib代理
public class Singer {
public void sing() {
System.out.println("lala...lala...");
}
}
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class CgAgent implements MethodInterceptor {
private Enhancer enhancer = new Enhancer();
public Object newInstance(Class clazz) {
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("Agent Before doSth.");
methodProxy.invokeSuper(o, objects);
System.out.println("Agent After doSth.");
return null;
}
}
public class TestCgAgent {
public static void main(String[] args) {
CgAgent agent = new CgAgent();
Singer singerProxy = (Singer) agent.newInstance(Singer.class);
singerProxy.sing();
}
}
cglib在https://github.com/cglib/cglib 下nodep jar包,否则会报ASM错误。