设计模式 之 动态代理

简介

静态代理是直接生成的组合方式进行操作, 动态代理在java 中是通过reflect反射机制实现的.

参考链接

https://blog.csdn.net/u012326462/article/details/81293186
https://www.bilibili.com/video/BV1mc411h719?p=11&spm_id_from=pageDriver

首先得关注两个类

  1. Proxy
java.lang.Object 
    java.lang.reflect.Proxy 

Proxy提供用于创建动态代理类和实例的静态方法,也是所有动态代理类的超类创建的方法。
主要关注

    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)

返回动态代理类对象.
@Param loader 用 getClassLoader()
ex: this.getClass().getClassLoader()
@Param interfaces 用 getInterfaces() 动态代理类需要实现的接口
ex: rent.getClass().getInterfaces()
@Param h
使用this 动态代理方法在执行时,会调用h里面的invoke方法去执行

  1. InvocationHandler
    public interface InvocationHandler
    InvocationHandler由调接口实现用处理程序的代理实例。
    每个代理实例都有一个关联的调用处理程序。代理实例上调用方法时,在方法调用编码并派往invoke方法的调用处理程序。
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        seeHouse();
        Object result = method.invoke(rent, args);
        return result;
    }

code

public class ProxyInvocationHandler implements InvocationHandler{
    private Rent rent;

    public void setRent(Rent rent){
        this.rent = rent;
    }

    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                rent.getClass().getInterfaces(), this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        seeHouse();
        Object result = method.invoke(rent, args);
        return result;
    }

    public void seeHouse() {
        System.out.println("中介看房子");
    }
}

public interface Rent {
    void rent();
}

public class Host implements Rent {
    @Override
    public void rent() {
        System.out.println("房东要出租");
    }
}

public class Client {
    public static void main(String[] args) {
        Host host = new Host();

        ProxyInvocationHandler pih = new ProxyInvocationHandler();
        pih.setRent(host);
        Rent proxy = (Rent) pih.getProxy();
        proxy.rent();
    }
}

image

Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14821338.html