设计模式(Design pattern)代理模式(Proxy Pattern)之动态代理(Dynamic Pattern)的 CGLIB 实现

CGLIB介绍

https://github.com/cglib/cglib


About
cglib - Byte Code Generation Library is high level API to generate and transform Java byte code. It is used by AOP, testing, data access frameworks to generate dynamic proxy objects and intercept field access.

JDK动态代理,必须对 interface 进行代理;而,CGLIB 能直接对 类 进行代理。

要设置 pom 文件

https://mvnrepository.com/artifact/cglib/cglib/3.3.0

<!-- https://mvnrepository.com/artifact/cglib/cglib -->
<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.3.0</version>
</dependency>

直接见代码

类 — 代理商

/**
 * 动态代理 - CGLIB : 代理商网点
 * @version 0.1
 * @author  BaiJing.biz
 */
public class AgentOutlets {

    public void sell() {
        System.out.println("Agent 代理商销售商品");
    }
}

工厂类


/**
 * 动态代理 - CGLIB : 代理商网点
 * @version 0.1
 * @author  BaiJing.biz
 */
public class ProxyFactory implements MethodInterceptor {

    private AgentOutlets agentOutlets =  new AgentOutlets();

    public AgentOutlets getProxyObject() {
        // 创建 Enhancer 对象
        Enhancer enhancer = new Enhancer();

        // 父类的字节码对象
        enhancer.setSuperclass(AgentOutlets.class);

        // 设置回调函数 , this 子实现类对象
        enhancer.setCallback(this);

        // 创建代理对象
        AgentOutlets proxyObjcet = (AgentOutlets) enhancer.create();


        return  proxyObjcet;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("inetercept 执行中 ... ");
        System.out.println("CGLIB 代理,销售点收取服务费用 ...");
        // 调用目标对象的方法
        Object object = method.invoke(agentOutlets, objects);
        return object;
    }

}

继承 implements MethodInterceptor  实现具体的代理点销售行为。

客户


public class CustomerRun {
    public static void main(String[] args) {

        // 代理工厂对象
        ProxyFactory factory = new ProxyFactory();

        // 获取代理对象
        Trade proxyObject = factory.getProxyObject();

        // Sell ,调用代理对象的方法
        proxyObject.sell();

    }
}

结果

 静态代理参考:

设计模式(Design pattern)代理模式(Proxy Pattern)之静态代理(Static Proxy)-CSDN博客

JDK 动态代理参考

设计模式(Design pattern)代理模式(Proxy Pattern)之动态代理(Dynamic Pattern)-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值