代理设计模式

1. 代理设计模式

代理设计模式主要对我们的方法前后实现增强。

2. 应用场景

  • 打印日志
  • Aop和事务Aop
  • Mybatis中 mapper接口
  • 全局捕获异常
  • Lcn、seata、分表分框架shadingjdbc 代理数据源
  • 自定义注解生效(反射技术+Aop)
  • Rpc远程调用技术代理设计模式

3.代理类优缺点

优点:实现扩展功能,对我们方法实现增强、安全性、冗余性提高代码复用机制。
缺点:生成非常多代理的class文件。

4. jdk动态代理

package com.tostyle.jdk;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
 * @author tostyle
 * 2022/4/6 15:05
 */
public class JdkInvocationHandler implements InvocationHandler {
    private Object target;
    public JdkInvocationHandler(Object o){
        this.target=o;
    }
    /**
     * 使用生成代理拦截回调
     * @param proxy 动态生成的代理类
     * @param method 接口中的方法
     * @param args 代理类参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("jdk动态代理开始");
        //调用目标方法  java的反射
        Object invoke = method.invoke(target, args);
        System.out.println("jdk动态代理结束");
        return invoke;
    }
    /**
     * 使用jdk创建代理类对象
     * @param <T>
     * @return
     */
    public <T> T getProxy(){
        //ClassLoader 读取代理类的class文件
        //interfaces 基于该接口拼接代理类的源代码
        //InvocationHandler this
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }
}


package com.tostyle.proxy.inter;

/**
 * @author tostyle
 * 2022/4/6 10:14
 */
public interface BookService {


    /**
     * 需要被代理的方法
     * @param bookName
     * @return
     */
    String addBook(String bookName);
}

package com.tostyle.proxy.inter;

/**
 * @author tostyle
 * 2022/4/6 13:49
 */
public class BookServiceImpl implements BookService{
    @Override
    public String addBook(String bookName) {
        System.out.println("tostyle"+bookName);
        return "tostyle"+bookName;
    }
}

5. 测试

package com.tostyle.reflect;
import com.tostyle.jdk.JdkInvocationHandler;
import com.tostyle.proxy.inter.BookService;
import com.tostyle.proxy.inter.BookServiceImpl;
/**
 * @author tostyle
 * 2022/4/6 15:15
 */
public class ProxyTest002 {
    public static void main(String[] args) {
        JdkInvocationHandler jdkInvocationHandler = new JdkInvocationHandler(new BookServiceImpl());
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        BookService proxy = jdkInvocationHandler.getProxy();
        String addBook = proxy.addBook("测试JDK代理类");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值