现在的位置: 首页 > 综合 > 正文

代理模式(Proxy)

2018年04月04日 ⁄ 综合 ⁄ 共 1707字 ⁄ 字号 评论关闭

作用:为其它对象提供一种代理,以控制外界对该对象的访问

 静态代理

 

代码:

/**

 * 代理对象(Proxy)  和   被代理对象(Target) 的共同接口

 * @author lyn

 * "出租" 的行为

 */

public interface ICanLease {

    public void lease();

}

 

/**

 * 房子的主人  (具有把房子出租出去的行为)

 * @authorlyn

 */

public class Landlord implements ICanLease{ 

    @Override

    public void lease() {

       System.out.println("房子的主人把房子出租出去...");

    }

}

 

/**

 * 万恶的房产中介  (同样具有把房子出租出去的行为)

 * @author lyn

 *

 */

public class LandlordProxy implements ICanLease{

    private ICanLease target;       //被代理的对象(即真正房子的主人)   

    public LandlordProxy(ICanLease target){

       this.target = target;

    }

    @Override

    publicvoid lease() {

       System.out.println("租出之前,黑心中介坑你一点");      

       target.lease();      //把被代理对象的房子出租      

       System.out.println("租出之后,黑心中介坑你一点");

    }   

}

/**

 * 悲摧的外来打工者

 * @author lyn

 */

publi cclass Client {

    public static void main(String[] args) {

       LandlordProxy proxy = new LandlordProxy(new Landlord());

       proxy.lease();

    }  

}

动态代理

//ProxyInvocationHandler.java 

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

/**

 * 代理对象把代理要做事交给本类对象去处理

 */

public class ProxyInvocationHandler implements InvocationHandler {   

    private Object target;   //要为其生成代理的对象   

    public void setTarget(Object target) {

       this.target = target;

    } 

    public ProxyInvocationHandler(){      

    }

   

    @Override

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {      

       System.out.println("真正做事之前做点坏事....");      

       Object ret = method.invoke(target, args);   

      
       System.out.println("做事之后再做点坏事....");      

       return ret;

    } 

    public ProxyInvocationHandler(Object target){

       this.target = target;

    }

}

 

//Clent.java 

import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Proxy;

/**

 * 使用

 */

public class Clent {

    public static void main(String[] args) {      

       InvocationHandler handler = new ProxyInvocationHandler(new String("123"));
      

       //动态生成一个代理对象(所属的类可能为$Proxy0,是JVM运行时动态生成的)

       CharSequence proxy = (CharSequence) Proxy.newProxyInstance(String.class.getClassLoader(),

              String.class.getInterfaces(), handler);
      

       proxy.toString();
      

    }

}


【上篇】
【下篇】

抱歉!评论已关闭.