java模式之动态代理

package proxy;
/**
 *
 * @author chen
 *
 */
public interface Subject {
 abstract public void request();
 abstract public void request2();
}


package proxy;

/**
 *
 * @author chen
 *
 */
public class RealSubject implements Subject {
 
 public RealSubject(){
 }

 public void request() {
  // TODO Auto-generated method stub
  System.out.println("From real subject.request().");
 }
 
 public void request2() {
  // TODO Auto-generated method stub
  System.out.println("From real subject.request2()");
 }
}

package proxy;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 *
 * @author chenweicai
 *
 */
public class DynamicSubject implements InvocationHandler {
 
 private Object sub;
 
 public DynamicSubject(){
 }
 
 public DynamicSubject(Object obj){
  this.sub = obj;
 }

 public Object invoke(Object proxy, Method method, Object[] args)
   throws Throwable {
  // TODO Auto-generated method stub
     System.out.println("before calling " + method);
     method.invoke(sub,args);
     System.out.println("after calling " + method);
  return null;
 }

}


package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.lang.reflect.Proxy;

/**
 *
 * @author chen
 *
 */
public class Client {
 static public void main(String[] args)
        throws Throwable{
    RealSubject rs = new RealSubject();  //在这里指定被代理类
    InvocationHandler ds = new DynamicSubject(rs);  //初始化代理类
    Class cls = rs.getClass();
  
    //以下是分解步骤
    /*Class c = Proxy.getProxyClass(cls.getClassLoader(),cls.getInterfaces()) ;
    Constructor ct=c.getConstructor(new Class[]{InvocationHandler.class});
    Subject subject =(Subject) ct.newInstance(new Object[]{ds});*/
  
    //以下是一次性生成
    Subject subject = (Subject) Proxy.newProxyInstance(cls.getClassLoader(),
    cls.getInterfaces(),ds );

    subject.request2();
   }
}

你可能感兴趣的:(java模式之动态代理)