23种设计模式-动态代理(JDK)

基本介绍:
1)代理对象,不需要实现接口,但是目标对象要实现接口,否则不能动态代理
2)代理对象的生成,是利用JDK的API,动态的内存中构建代理对象
3)动态代理也叫做:JDK代理,接口代理

JDK中生成代理对象的API
1)代理类所在包:java.lang.reflect.Proxy
2)JDK实现代理只需要使用newProxyInstance方法,但是方法需要三个参数,完整的写法是:
Static Object newProxyInstance(ClassLoader loader,Class<?>[] instance,InvocationHandler h)
在这里插入图片描述

public interface ITeacherDao {
    
    
    void teach();
}

public class TeacherDao implements ITeacherDao {
    
    
    @Override
    public void teach() {
    
    
        System.out.println("老师授课中。。。。。");
    }
}

public class ProxyFactory {
    
    

    //要被代理的对象
    private Object target;

    public ProxyFactory(Object target) {
    
    
        this.target = target;
    }

    /*
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
       //1.ClassLoader loader :指定当前目标对象使用的类加载器,获取加载器的方法固定
       //2.Class<?>[] interface :目标对象实现的接口类型,使用泛型方法确认类型
       //3.InvocationHandler h:事情处理,执行目标对象的方法时,会触发事情处理器方法,
         会把当前执行的目标方法对象作为参数传入
            */
    public Object getProxyInstance(){
    
    
        return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
    
    
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
                System.out.println("JDK代理开始~~");
                Object returnVal = method.invoke(target, args);
                System.out.println("JDK代理提交~~");
                return returnVal;
            }
        });
    }
}

public class Client {
    
    
    public static void main(String[] args) {
    
    
        //创建目标对象
        ITeacherDao target=new TeacherDao();
        //创建代理对象
        ITeacherDao teacherDaoProxy=(ITeacherDao)new ProxyFactory(target).getProxyInstance();
        //proxyInstance =class com.sun.proxy.$Proxy0内存中生成了代理对象
        System.out.println("proxyInstance =" + teacherDaoProxy.getClass());
        teacherDaoProxy.teach();
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44468025/article/details/117394381