javascript学习指南|Java笔记之对象代理实例

时间:2019-02-16  来源:js教程  阅读:
 代码如下

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


//代理需要实现的接口
interface IVehical {

    //例如我这里写了两个接口
    void run();
    void say();
}

//concrete implementation
 class Car implements IVehical{

    //下面这两个方法,作为接口的实现方法,如果接口中没有这些方法,而在这里出现了多余的方法程序将编译不过。
    //每次调用这两个方法都会触发代理对象中的invoke方法。
    public void run() {
    System.out.println("Car is running");
    }
   
    public void say()
    {
        System.out.println("just one!");
    }

}

//proxy class
//这个类是用来创建代理对象的,这里只是对它进行了简单的封装
class VehicalProxy {

    private IVehical vehical;

    public VehicalProxy(IVehical vehical) {
    this.vehical = vehical;
    }
    //这个方法返回创建后的对象代理
    public IVehical create(){
    final Class[] interfaces = new Class[]{IVehical.class};
    final VehicalInvacationHandler handler = new VehicalInvacationHandler(vehical);
   
    return (IVehical) Proxy.newProxyInstance(IVehical.class.getClassLoader(), interfaces, (InvocationHandler) handler);
    }
    //这个是跟代理对象绑定的一个处理器,www.111cn.net每次调用对象代理中的方法都会触发这个处理器中的invoke方法
    class VehicalInvacationHandler implements InvocationHandler{

    private final IVehical vehical;
   
    public VehicalInvacationHandler(IVehical vehical) {
        this.vehical = vehical;
    }

    //每当执行对象代理的say或者call(只要是IVehical接口中的方法)就会触发invoke被执行
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {

        System.out.println("--before running...");
        Object ret = method.invoke(vehical, args);
        System.out.println("--after running...");
       
        return ret;
    }
   
    }
}

class Main {
    public static void main(String[] args) {
   
    IVehical car = new Car();
    VehicalProxy proxy = new VehicalProxy(car);
   
    IVehical proxyObj = proxy.create();
    proxyObj.say();
    }
}

/*
 * 程序运行之后将打印如下信息,因此我们可以看出对象的代理可以往特定对象的方法中添加附带的执行代码,
 * 这个的作用在我们需要对一个做日志或者bug调试的时候非常有作用,因为我们不应该把调试代码或者是打
 * 印日志代码写在对象中,这样我们就可以将日志的代码添加到对象的代理中,从而将业务与程序的框架相
 * 关的功能分离,从而保证了代码的“纯净性”。
 * output:
 * --before running...
 * Car is running
 * --after running...
 * */

javascript学习指南|Java笔记之对象代理实例

http://m.bbyears.com/wangyezhizuo/48066.html

推荐访问:java学习路线
相关阅读 猜你喜欢
本类排行 本类最新