java代理模式

一.JDK代理机制

        1.定义发送短信的接口

        public interface SmsService {
    String send(String message);
}

        2.实现发送短信的接口

                        public class SmsServiceImpl implements SmsService {
            public String send(String message) {
                System.out.println("send message:" + message);
                return message;
            }        
        }

        3.定义一个JDK动态代理类

                

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

/**
 * @author shuang.kou
 * @createTime 2020年05月11日 11:23:00
 */
public class DebugInvocationHandler implements InvocationHandler {
    /**
     * 代理类中的真实对象
     */
    private final Object target;

    public DebugInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws InvocationTargetException, IllegalAccessException {
        //调用方法之前,我们可以添加自己的操作
        System.out.println("before method " + method.getName());
        Object result = method.invoke(target, args);
        //调用方法之后,我们同样可以添加自己的操作
        System.out.println("after method " + method.getName());
        return result;
    }
}

        4.获取动态代理的工厂类

                public class JdkProxyFactory {
    public static Object getProxy(Object target) {
        return Proxy.newProxyInstance(
                target.getClass().getClassLoader(), // 目标类的类加载器
                target.getClass().getInterfaces(),  // 代理需要实现的接口,可指定多个
                new DebugInvocationHandler(target)   // 代理对象对应的自定义 InvocationHandler
        );
    }
}

        5.实际使用

        SmsService smsService = (SmsService) JdkProxyFactory.getProxy(new SmsServiceImpl());
        smsService.send("java");

        解析:

        代理类的由来;是由JdkProxyFactory.getProxy()方法创建的

        

  • JdkProxyFactory.getProxy() 方法会返回一个代理对象,它是 SmsService 接口的实现类(通过动态代理创建)。

  • 这个代理类实现了 SmsService 接口,并在方法调用时将请求转发到 DebugInvocationHandler 中的 invoke() 方法。

你可能感兴趣的:(java,代理模式,servlet)