【设计模式】Java动态代理

  • 动态代理可以实现事务控制。让代码不再臃肿和繁琐。

动态代理

  • 特点:字节码随用随创建,随用随加载。
  • 作用:不修改源码的基础上对方法增强。
  • 分类:基于接口的动态代理和基于子类的动态代理。

基于接口的动态代理

  • 涉及的类:Proxy

  • 提供者:JDK官方

  • 如果创建代理对象? 使用Proxy类中的newProxyInstance方法。

  • 创建代理对象的要求:被代理类最少实现一个接口,如果没有,则不能使用。


  • newProxyInstance方法的参数:
  1. ClassLoader :它是用于加载代理对象字节码的。是被代理对象使用相同的类加载器。固定写法(代理谁,就写谁的ClassLoader)
  2. Class[] :字节码数组。它是用于让代理对象和被代理对象有相同的方法。(两个实现同一个接口,它们就有共同的方法)。固定写法。
  3. InvocationHandler :用于提供增强的代码。它是让我们写如何代理。一般都是写一个InvocationHandler 接口的实现类。此方法的实现类都是谁用谁写的。
//实现IProducer接口的被代理对象Producer 
public class Producer implements IProducer {
    @Override
    public void saleService(Float money) {
        System.out.println("销售产品,赚了"+money);
    }
    @Override
    public void afterService(Float money) {
        System.out.println("提供售后,赚了"+money);
    }
}

//模拟
public class Client {
    public static void main(String[] args) {
        Producer producer = new Producer();
        //代理前
        producer.saleService(1000f);
        producer.afterService(100f);
        //代理对象producerProxy ,接口IProducer 
        IProducer producerProxy = (IProducer)Proxy.newProxyInstance(producer.getClass().getClassLoader(), producer.getClass().getInterfaces(), new InvocationHandler() {
            /**
             * 作用:执行被代理对象的任何借口方法都会经过该方法。
             * 方法参数的含义。
             * @param proxy     代理对象的引用。
             * @param method    当前执行的方法。(被代理对象的方法。也可能没有代理。)
             * @param args      当前执行的方法所需的参数。
             * @return          和被代理对象有相同的返回值。
             * @throws Throwable
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                
                Float money = (Float) args[0];
                if ("saleService".equals(method.getName())){
                    return  method.invoke(producer,money*0.8f);
                }
                if("afterService".equals(method.getName())){
                    return method.invoke(producer,money+1.0f);
                }
                return method.invoke(producer,args);
            }
        });
        System.out.println("动态代理后");
        producerProxy.saleService(1000f);
        producerProxy.afterService(100f);
    }
}


基于子类的动态代理

  • 需要第三方jar 的支持
  • 同时需要一个依赖
<dependency>
   <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.3.0</version>
</dependency>

asm可自动导入。
在这里插入图片描述


  • 涉及的类:Enhancer

  • 提供者:第三方cglib库

  • 如果创建代理对象? 使用Enhancer类中的create方法。

  • 创建代理对象的要求:被代理类不能是最终类。


  • create方法的参数:
  1. Class:指定被代理对象的字节码。
  2. callback:用于提供增强的代码。它是让我们写如何代理。一般都是写一个接口的实现类。此方法的实现类都是谁用谁写的。
  3. 我们一般写的都是该接口的子接口实现类,MethodInterceptor
//没有接口,通过基于子类的动态代理
public class Producer{
    public void saleService(Float money) {
        System.out.println("销售产品,赚了"+money);
    }
    public void afterService(Float money) {
        System.out.println("提供售后,赚了"+money);
    }
}

public class Client {
    public static void main(String[] args) {
        Producer producer = new Producer();
        Producer cglibproducer  = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
            /**
             * 被代理对象的任何方法都会经过该方法
             * @param proxy
             * @param method
             * @param args
             *      以上三个参数和基于接口的动态代理中invoke方法的参数是一样的。
             * @param methodProxy 当前执行方法的代理对象
             * @return
             * @throws Throwable
             */
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                //被代理对象的方法。
                Float money = (Float) args[0];
                if ("saleService".equals(method.getName())) {
                    return method.invoke(producer, money * 0.8f);
                }
                if ("afterService".equals(method.getName())) {
                    return method.invoke(producer, money + 1.0f);
                }
                return method.invoke(producer, args);
            }
        });
        cglibproducer.saleService(1000f);
        cglibproducer.afterService(1000f);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nickkkkkkkkk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值