设计模式之代理模式

动态代理的概述和实现

> 动态代理概述
1.代理:本来应该自己做的事情,请了别人来做,被请的人就是代理对象。 举例:春节回家买票让人代买
2.在Java中java.lang.reflect包下提供了一个Proxy类和一个InvocationHandler接口
3.通过使用这个类和接口就可以生成动态代理对象。
4.JDK提供的代理只能针对接口做代理。
5.我们有更强大的代理cglib
6.Proxy类中的方法创建动态代理类对象 Proxy 通过 newProxyInstance(loader,interfaces,h)创建代理对象
InvocationHandler的invoke(proxy,method, args)方法会拦截方法的调用

package lesson.animal.proxy;

import javax.sound.midi.Soundbank;
import javax.swing.event.MouseInputAdapter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * User: 彭家琪
 * Date: 2019/9/11   19:59
 */
public class ProxyDemo {

    public static void main(String[] args) {
        UserServerImpl userServer = new UserServerImpl();
       /* userServer.registUser();
        userServer.delUser();*/

        //创建代理对象
        UserServer proxy = (UserServer) Proxy.newProxyInstance(userServer.getClass().getClassLoader(),
                userServer.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println(method);
                        System.out.println("权限校验。。");

                        Object reoj = method.invoke(userServer, args);

                        System.out.println("日志记录。。");

                        return reoj;
                    }
                });
        proxy.registUser();
        proxy.delUser();
    }
}
interface UserServer{
    public void registUser();
    public void delUser();
}
class UserServerImpl implements UserServer{

    @Override
    public void registUser() {
        System.out.println("注册用户");
    }

    @Override
    public void delUser() {

        System.out.println("删除用户");
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章