设计模式(一)动态代理

一、概念

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

二、常规例子

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动态代理

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

相关推荐
Zyy~5 小时前
《设计模式》工厂方法模式
设计模式·工厂方法模式
ikkkkkkkl8 小时前
C++设计模式:面向对象设计原则
c++·设计模式·面向对象
whitepure12 小时前
万字详解Java中的面向对象(二)——设计模式
java·设计模式
稚辉君.MCA_P8_Java14 小时前
豆包 Java的23种设计模式
java·linux·jvm·设计模式·kubernetes
快乐的划水a1 天前
组合模式及优化
c++·设计模式·组合模式
Zyy~1 天前
《设计模式》装饰模式
java·设计模式
落霞的思绪1 天前
Java设计模式详细解读
java·开发语言·设计模式
是2的10次方啊1 天前
🚀 JDK设计模式大揭秘:23种模式藏在你每天在用的类里
设计模式
步行cgn1 天前
设计模式(Design Patterns)
设计模式
Zyy~1 天前
《设计模式》代理模式
设计模式·代理模式