设计模式-代理模式

代理模式

应用场景:不该变源代码,给源代码增加功能。

在Java中,常用的代理有JDK动态代理和cglib动态代理。JDK动态代理由java.lang.reflect包下的Proxy提供的,基于接口生成的代理类,实现对目标类的代理;cglib是由Oracle提供的Java开发工具包,采用字节码技术,直接修改字节码并生成代理子类。

注意:JDK动态代理中,调用方法时其代理类并不知道目标类的具体方法,因此需要通过反射来进行调用,效率很低。

JDK实现动态代理

java 复制代码
public class Person implements IPerson {
    @Override
    public void eat(){
        System.out.println("开始吃饭");
    }
}

1.定义接口,定义需要代理的方法

java 复制代码
public interface IPerson {
    public void eat();
}

2.定义类并创建代理对象

java 复制代码
    public static IPerson createPersonProxy(Person person){
        IPerson iPersonProxy = (IPerson) Proxy.newProxyInstance(PersonProxy.class.getClassLoader()
                , new Class[]{IPerson.class}
                , new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if(method.getName() == "eat"){
                            System.out.println("拿筷子");
                            System.out.println("拿碗");
                        }

                        return method.invoke(person ,args);
                    }
                });
        return iPersonProxy;
    }
}

3.调用代理对象的方法

java 复制代码
public class Demo {
    public static void main(String[] args) {
        Person person = new Person();
        IPerson personProxy = PersonProxy.createPersonProxy(person);
        personProxy.eat();
    }
}

CGLIB实现动态代理

java 复制代码
public class Person{
    public void eat(){
        System.out.println("开始吃饭");
    }
}
java 复制代码
public class PersonProxy implements MethodInterceptor {
    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clazz){
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        //通过字节码技术动态创建子类实例
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if(method.getName().equals("eat")){
            System.out.println("拿筷子");
            System.out.println("拿碗");
        }

        //通过代理类调用父类中的方法
        Object result = methodProxy.invokeSuper(o, objects);

        return result;
    }
}
相关推荐
reddingtons19 小时前
【游戏宣发】PS “生成式扩展”流,30秒无损适配全渠道KV
游戏·设计模式·新媒体运营·prompt·aigc·教育电商·游戏美术
sxlishaobin21 小时前
设计模式之桥接模式
java·设计模式·桥接模式
晴殇i1 天前
package.json 中的 dependencies 与 devDependencies:深度解析
前端·设计模式·前端框架
HL_风神1 天前
设计原则之单一职责原则
c++·学习·设计模式·单一职责原则
GISer_Jing1 天前
智能体基础执行模式实战:拆解、决策、并行、自优化
人工智能·设计模式·aigc
moxiaoran57531 天前
Java设计模式的运用
java·开发语言·设计模式
GISer_Jing1 天前
提示链(Prompt Chaining)、路由、并行化和反思
人工智能·设计模式·prompt·aigc
AM越.1 天前
Java设计模式超详解--代理设计模式(含uml图)
java·设计模式·uml
a3535413821 天前
设计模式-中介者模式
c++·设计模式·中介者模式
a3535413821 天前
设计模式-适配器模式
设计模式·适配器模式