代理模式 Proxy

代理类模式

在不改变原有类的基础上,代理一个类,并对其方法前后进行增强

1.Java动态代理:代理实现某一个接口的类或接口本身

接口类

public interface Body {
    void doThing();
}

实现类:

public class Person implements Body{
    @Override
    public void doThing() {
        System.out.println("大人做事情");
    }
}

代理类:

public class JdkProxyPerson {
    public static Object getBean(Object target) {
        return Proxy.newProxyInstance(JdkProxyPerson.class.getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("jdk proxy start----");
                Object invoke = method.invoke(target, args);
                System.out.println("jdk proxy end----");
                return invoke;
            }
        });
    }
}

测试类:

public class TestProxy {
    public static void main(String[] args) {
        Person person = (Person)BeanFactory.getBean("person");
        Body bean = (Body) JdkProxyPerson.getBean(person);
        bean.doThing();
    }
}

jdk proxy start----
孩子在玩耍
大人做事情
jdk proxy end----

2.Cglib动态代理:代理基础类 填补Jdk代理的缺憾

依赖:

<dependency>
    <groupId>cglib</groupId>
    <artifactId>cglib</artifactId>
    <version>3.2.7</version>
</dependency>

基础类:

public class Child {
    public void play(){
        System.out.println("孩子在玩耍");
    }
}

代理类:

public class CglibProxyPerson {
    public static Object createProxy(Class<?> clazz, Callback callback) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(callback);
        return enhancer.create();
    }

    /**
     * 拦截器
     */
    public static class MyInterceptor implements MethodInterceptor {
        public MyInterceptor() {
        }

        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            System.out.println("cglib start...");
            Object result = proxy.invokeSuper(obj, args);
            System.out.println("cglib end...");
            return result;
        }
    }
}

测试类:

public class TestProxy {
    public static void main(String[] args) {
        Child proxy = (Child)CglibProxyPerson.createProxy(Child.class, new CglibProxyPerson.MyInterceptor());
        proxy.play();
    }
}

cglib start...
孩子在玩耍
cglib end...

posted @ 2023-04-01 15:22  土木转行的人才  阅读(16)  评论(0编辑  收藏  举报