靜態代理:
ISubject:
/** * @author com.tiantian * @version 建立時間:2012-11-20 下午1:49:29 */public interface ISubject { public void request();}
RealSubject(真實角色):
/** * @author com.tiantian * @version 建立時間:2012-11-20 下午1:51:37 */public class RealSubject implements ISubject{ @Override public void request() { System.out.println("realSubject requesting"); }}
ProxySubject(代理類):
/** * @author com.tiantian * @version 建立時間:2012-11-20 下午1:52:22 */public class ProxySubject implements ISubject{ private RealSubject realSubject; public ProxySubject() { realSubject = new RealSubject(); } @Override public void request() { System.out.println("do something before"); realSubject.request(); System.out.println("do something after"); }}
Test(用戶端測試):
/** * @author com.tiantian * @version 建立時間:2012-11-20 下午1:54:47 */public class Test { public static void main(String[] args) { ISubject proxySubject = new ProxySubject(); proxySubject.request(); }}
------------------------------------------------------------------------------------------------------------------------------
動態代理:
ISubject:
/** * @author com.tiantian * @version 建立時間:2012-11-20 下午2:51:31 */public interface ISubject { public void request();}
RealSubject:
/** * @author com.tiantian * @version 建立時間:2012-11-20 下午2:52:00 */public class RealSubject implements ISubject{ @Override public void request() { System.out.println("realSubject requesting"); }}
SubjectInvocationHandler(調用處理類):
/** * @author com.tiantian * @version 建立時間:2012-11-20 下午2:54:38 * 調用處理類 */public class SubjectInvocationHandler implements InvocationHandler{ private Object obj; public SubjectInvocationHandler(Object obj) { this.obj = obj; } /** * 組建代理程式類工廠 * @author com.tiantian * @param realObj * @return 返回產生的代理類 */ public static Object getProxyInstanceFactory(Object realObj){ Class<?> classType = realObj.getClass(); return Proxy.newProxyInstance(classType.getClassLoader(), classType.getInterfaces(), new SubjectInvocationHandler(realObj)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("before"); method.invoke(obj, args); System.out.println("after"); return null; }}
Test:
/** * @author com.tiantian * @version 建立時間:2012-11-20 下午2:56:25 */public class Test { public static void main(String[] args) { RealSubject realSubject = new RealSubject();// InvocationHandler handler = new SubjectInvocationHandler(realSubject);// ISubject subject = (ISubject)Proxy.newProxyInstance(realSubject.getClass().getClassLoader(),// realSubject.getClass().getInterfaces(), handler); ISubject subject = (ISubject)SubjectInvocationHandler.getProxyInstanceFactory(realSubject); subject.request(); }}