设计模式(一)动态代理

一、概念

通过代理对象访问目标对象,增强目标对象的方法

二、常规例子

JDK动态代理(接口)

java 复制代码
interface HelloInterface{

    void helloWorld();
}
class HelloImpl implements HelloInterface{

    @Override
    void helloWorld()
    {
        System.out.println("helloWorld!");
    }

}

class HelloProxy implements helloInterface{
    HelloImpl hello;
    HelloProxy(HelloImpl hello){
    this.hello=hello;
    }
    @Override
    void proxyHelloWorld()
    {
        System.out.println("方法前增强!");
        hello.helloWorld();
        System.out.println("方法后增强!");
    }

}

public class test{
    public static void main(String[] args) {
        HelloImpl hello=new HelloImpl();
        HelloProxy proxy=new HelloProxy(hello);
        proxy.helloWorld();
    }

}
//结果
//方法前增强!
//helloWorld!
//方法后增强!

CGLIB动态代理(子类)

java 复制代码
class Hello{
    void helloWorld()
    {
        System.out.println("helloWorld!");
    }
}
class HelloProxy extends Hello{
    HelloImpl hello;
    HelloProxy(HelloImpl hello){
    this.hello=hello;
    }
    void helloWorld()
    { 
        System.out.println("方法前增强!");
        hello.helloWorld();
        System.out.println("方法后增强!");
    }

}

public class test{
    public static void main(String[] args) {
        HelloImpl hello=new HelloImpl();
        HelloProxy proxy=new HelloProxy(hello);
        proxy.helloWorld();
    }

}
//结果
//方法前增强!
//helloWorld!
//方法后增强!
三、在SpringAOP中的应用

1、JDK动态代理

基于接口(Java只能单继承,想要目标类与代理类产生联系,只能实现统一接口)

目标对象需要实现接口,代理对象不需要实现接口(看Java源码及反编译知,动态在内存中生成的真实代理类实现了目标接口)

2、CGLIB动态代理

动态在内存中生成目标类的子类来实现代理

相关推荐
拉里小猪的迷弟17 分钟前
设计模式-创建型-常用:单例模式、工厂模式、建造者模式
单例模式·设计模式·建造者模式·工厂模式
严文文-Chris2 小时前
【设计模式-中介者模式】
设计模式·中介者模式
刷帅耍帅2 小时前
设计模式-中介者模式
设计模式·中介者模式
刷帅耍帅3 小时前
设计模式-组合模式
设计模式·组合模式
刷帅耍帅4 小时前
设计模式-命令模式
设计模式·命令模式
码龄3年 审核中4 小时前
设计模式、系统设计 record part03
设计模式
刷帅耍帅4 小时前
设计模式-外观模式
设计模式·外观模式
刷帅耍帅5 小时前
设计模式-迭代器模式
设计模式·迭代器模式
liu_chunhai5 小时前
设计模式(3)builder
java·开发语言·设计模式
刷帅耍帅5 小时前
设计模式-策略模式
设计模式·策略模式