代理模式(接口和子类)

来源:互联网 发布:淘宝网手机网页版 编辑:程序博客网 时间:2024/06/05 01:02

接口:

package com.alice.Proxy;

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

public class Client{
         public static void main(String[] args) {
   //2.改final
         final Springbrothder sb=new Springbrothder();
    /*     Proxy proxy=(Proxy) Proxy.newProxyInstance(sb.getClass().getClassLoader(), sb.getClass().getInterfaces(), new InvocationHandler() {
  //1.必须是Hummer 类 
    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable {
     // TODO Auto-generated method stub
     return null;
    }
   });
  
   */
         
          Hummer proxy=(Hummer) Proxy.newProxyInstance(sb.getClass().getClassLoader(), sb.getClass().getInterfaces(), new InvocationHandler() {
           //必须是Hummer 类 
             @Override
             public Object invoke(Object proxy, Method method, Object[] args)
               throws Throwable {
              if("sing".equals(method.getName())){
               double money=(Double)args[0];
               if(money>=10000)
               return  method.invoke(sb, money/2);
              }
              if("dance".equals(method.getName())){
               method.invoke(sb, 20000);
              }
              return null;
             }
            });
         
          proxy.sing(10); //3.调用 proxy
          proxy.sing(10000);
  }
 

}


 


子类:

package com.alice.Proxy2;


import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;

public class Client {

 
 public static void main(String[] args) {
  final Springbrothder sb=new Springbrothder();
 
  Springbrothder client=(Springbrothder)Enhancer.create(Springbrothder.class,new InvocationHandler() {
  
   @Override
   public Object invoke(Object proxy, Method method, Object[] args)
     throws Throwable {
    if("sing".equals(method.getName())){
     double money=(Double)args[0];
     if(money>=10000)
     return  method.invoke(sb, money/2);
    }
    if("dance".equals(method.getName())){
     method.invoke(sb, 20000);
    }
    return null;
   }
  });

  client.sing(10); //3.调用 proxy
  client.sing(10000);
}
}

原创粉丝点击