设计模式(一)动态代理

一、概念

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

二、常规例子

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

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

相关推荐
今儿敲了吗18 小时前
面向对象(三)——设计模式
笔记·设计模式
蜡笔小马19 小时前
08.C++设计模式-享元模式
c++·设计模式·享元模式
qq_3813385021 小时前
Vue3 组合式函数设计模式:从基础封装到高级复用实战
前端·vue.js·设计模式
geovindu1 天前
go: Lock/Mutex Pattern
开发语言·后端·设计模式·golang·互斥锁模式
学习中.........1 天前
常见设计模式
java·设计模式
多加点辣也没关系2 天前
设计模式-抽象工厂模式
java·设计模式·抽象工厂模式
洛水水2 天前
设计模式入门:从设计原则到核心模式
c++·设计模式
多加点辣也没关系2 天前
设计模式-组合模式
设计模式·组合模式
多加点辣也没关系2 天前
设计模式-外观模式
设计模式·外观模式
咖啡八杯2 天前
GoF设计模式——抽象工厂模式
java·后端·spring·设计模式·抽象工厂模式