16.设计模式-代理模式-jdk动态代理

//1.定义接口
//2.接口实现
//3.定义代理工厂,代理对象必须实现接口
//4.测试
public interface IStudentDao {
public String study(String name);
}

public class StudentDao implements IStudentDao {
public String study(String name) {
System.out.println(name + " 正在学习中....");
return "学习结束!";
}
}

public class ProxyFactory {

//维护一个目标对象,Object
private Object target;

//构造器,对target进行初始化
public ProxyFactory(Object target) {
    this.target = target;
}


public Object getProxyInstance(){
    /**
     * loader:指定当前目标对象使用的类加载器,获取加载器的方法固定
     * interfaces:目标对象实现的接口类型,使用泛型方法确认类型
     * InvocationHandle:事情处理,执行目标对象的方法时,会触发事情处理器方法
     */
    return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            System.out.println("开始jdk代理..");
            return method.invoke(target,args);
        }
    });
}

}

public class Test {
public static void main(String[] args) {
IStudentDao target =new StudentDao();
ProxyFactory factory=new ProxyFactory(target);
IStudentDao instance = (IStudentDao)factory.getProxyInstance();
String r =instance.study("李四");
System.out.println(r);
}
}

posted @ 2022-10-11 22:11  NIANER2011  阅读(18)  评论(0编辑  收藏  举报