设计模式之动态代理模式

  代理模式分动态和静态两种,下面重点理解动态代理:

JDK动态代理是通过Java反射机制动态的为具体实现生成代理类,从而实现委托事务。代理类不实现具体业务,只是为委托类进行预处理消息、过滤消息,然后再把消息传递给委托类,由委托类进行具体实现。

下面通过一个简单的示例来展示动态代理的具体实现。

1、首先定义接口

UserService
public interface UserService {
    public void select();
    public void update();
}

2、实现接口类

UserServiceImp
public class UserServiceImp implements UserService {
    private static final String TAG = "UserServiceImp";

    @Override
    public void select() {
        System.out.println(" 具体查询的实现在此... ");
    }

    @Override
    public void update() {
        System.out.println(" 具体更新的实现在此... ");

    }
}

3、实现

InvocationHandler

public class ProxyHandler implements InvocationHandler {
    private Object object ;

    public  ProxyHandler(Object object){
        this.object =object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Before invoke "  + method.getName()+" at time "+ System.currentTimeMillis());
        method.invoke(object, args);
        System.out.println("After invoke " + method.getName()+" at time "+ System.currentTimeMillis());
        return null;
    }

4、调用代理

Proxy

    public static void main(String[] args) {


        System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        UserService hello = new UserServiceImp();

        InvocationHandler handler = new ProxyHandler(hello);

        UserService proxyHello = (UserService) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), handler);

        proxyHello.select();
        proxyHello.update();
}

结果输出:

Before invoke select at time 1583291583921
 具体查询的实现在此... 
After invoke select at time 1583291583921
Before invoke update at time 1583291583921
 具体更新的实现在此... 
After invoke update at time 1583291583921
通常我们通过代理实现对系统调用的性能指标进行监控,为了将非业务逻辑与业务逻辑解耦,如果使用Spring框架,使用AOP更加方便,AOP底层就是JDK或CGLIB动态代理实现的。

原文地址:https://www.cnblogs.com/Fly-sky/p/12408440.html