代理模式-JDK Proxy
使用JDK支持的代理模式, 动态代理
场景如下: 本文例子代理了ArrayList, 在ArrayList每次操作时, 在操作之前和之后都进行一些额外的操作.
ArrayListProxy类
这里是代理的实现.
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; public class ArrayListProxy implements InvocationHandler { private Object proxy; public ArrayListProxy(Object obj) { this.proxy = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Exception { System.out.println("before calling " + method); if (args != null) { for (Object arg : args) { System.out.println(arg); } } Object o = method.invoke(this.proxy, args); System.out.println("after calling " + method); return o; } }
MyUtils类
封装了Proxy.newProxyInstance()方法, 方便取得代理对象.
import java.lang.reflect.Proxy; public class MyUtils { public static Object getProxy(Object obj) { Class cls = obj.getClass(); return Proxy.newProxyInstance( cls.getClassLoader(), cls.getInterfaces(), new ArrayListProxy(obj) ); } }
Main
在这里进行运行测试
import java.util.ArrayList; import java.util.List; @SuppressWarnings("unchecked") public class Main { public static void main(String[] args) { List realList = new ArrayList<String>(10); List proxyList = (List) MyUtils.getProxy(realList); proxyList.add("New"); System.out.print(" "); proxyList.add("York"); } }