设计模式(一)动态代理

一、概念

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

二、常规例子

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

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

相关推荐
拳打南山敬老院1 小时前
你的 Agent 可能并不需要过度工程化:一次从 LangGraph 到极简 Agent 的架构反思
人工智能·设计模式
萌小鱼要阳光3 小时前
八种常见的设计模式
设计模式
geovindu5 小时前
python: Bridge Pattern
python·设计模式·桥接模式
Anurmy11 小时前
设计模式之构建器模式
设计模式
鱼骨不是鱼翅13 小时前
个人简历面试复习-----设计模式篇(一)
设计模式
电子科技圈14 小时前
从工具到平台:如何化解跨架构时代的工程开发和管理难题
人工智能·设计模式·架构·编辑器·软件工程·软件构建·设计规范
Anurmy15 小时前
设计模式之装饰模式
设计模式
TimberWill16 小时前
优化if else过多的方案(含设计模式处理方式)
java·设计模式
@insist12316 小时前
软件设计师-结构型与行为型设计模式全解:软考设计模式考点一站式通关
设计模式·软考·软件设计师·软件水平考试
JTCC18 小时前
Java 设计模式西游篇 - 第五回:装饰者模式添法力 悟空披挂新战袍
java·观察者模式·设计模式