首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Dynamic Proxy方式

2012-10-10 
Dynamic Proxy模式ProxyFactory类package com.zzq.proxyimport java.lang.reflect.InvocationHandlerimp

Dynamic Proxy模式
ProxyFactory类

package com.zzq.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class ProxyFactory implements InvocationHandler{ private Object target;public ProxyFactory() {}public void setTarget(Object target) {this.target = target;}public Object createProxyBean() {return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);}public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {Object result = null;try {this.before();result = method.invoke(target, args);this.afert();} catch (Exception e) {afterThrow(e);}return result;}public void before() {System.out.println("before");}public void afert() {System.out.println("afert");}public void afterThrow(Throwable t) {System.out.println("afterThrow");if(t instanceof InvocationTargetException) {t = t.getCause();System.out.println(t.getMessage());} else {System.out.println(t.getMessage());}}}

package com.zzq.proxy;public interface SimpleBean {public void sayHello();public void throwException();}

package com.zzq.proxy;public class SimpleBeanImpl implements SimpleBean {public void sayHello() {System.out.println("hello proxy pattern!");}public void throwException() {throw new RuntimeException("出错了");}public static void main(String[] args) {ProxyFactory factory = new ProxyFactory();factory.setTarget(new SimpleBeanImpl());SimpleBean proxy = (SimpleBean)factory.createProxyBean();proxy.sayHello();proxy.throwException();}}

热点排行