最近在学设计模式,这里介绍下动态代理模式及总结:
在平时开发项目中比如添加日志,在每个action 前或后会加写日志,来记录请求信息,这里如果每个action的方法后面加会很多也会很复杂这里我们一般采用的是用spirng的AOP(如果你用spring的话)实际springAOP 的设计也是用到了动态代理模式和适配器模式这里写下代码:
这先举个列子来说明下动态代理模式,我以数学计算为例,每次计算前后都会加上一些日志如下:
public interface ArithmeticCalculator { int add(int i,int j); int div(int i,int j); }
下面添加一个计算的实现类:
@Component public class ArithmeticCalculatorImpl implements ArithmeticCalculator{ @Override public int add(int i, int j) { return i + j; } @Override public int div(int i, int j) { return i/j; } }
下面添加一个在结果返回前打印一行日志:
@Component public class ArithmeticCalculatorProxy { @Autowired private ArithmeticCalculator target; public ArithmeticCalculator getLoggingProxy(){ ArithmeticCalculator proxy = null; ClassLoader loader = target.getClass().getClassLoader(); Class[] interfaces = new Class[]{ArithmeticCalculator.class}; InvocationHandler h = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("begin execute "+method.getName()+" method"); Object result = method.invoke(target, args); System.out.println(method.getName()+" execute success result is :"+result); return result; } }; proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader,interfaces,h); return proxy; } }
再写一个测试程序:
public class Main { public static void main(String[] args){ ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:cc.MAT-INFO/applicationContext.xml"); ArithmeticCalculator proxy =ctx.getBean(ArithmeticCalculatorProxy.class).getLoggingProxy(); proxy.add(2,3); proxy.div(9, 3); } }
执行结果:
四月 02, 2015 10:35:35 上午 org.springframework.context.support.AbstractApplicationContext prepareRefresh 信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5d855f: startup date [Thu Apr 02 10:35:35 CST 2015]; root of context hierarchy 四月 02, 2015 10:35:35 上午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 信息: Loading XML bean definitions from class path resource [cc.MAT-INFO/applicationContext.xml] begin execute add method add execute success result is :5 begin execute div method div execute success result is :3
代码比较简单,故没写注释