代理模式的作用是控制和管理对象的访问权限;它的优点是:想要找代理的对象,可以不用每次都自己实现某个功能,可以把某个方法的调用权限,交给代理类来完成。一般分为 静态代理 和 动态代理 。要实现代理模式,代理类和目标类需要实现同样的接口。 这个以上传业务举例:
//我们定一个接口 interface IUpload { void onUpload(); } //定义目标类,实现前面接口 public static class CommonUploader implements IUpload { @Override public void onUpload() { System.out.println("普通上传啦~"); } } //定义代理类,实现同意的接口 public static class ProxyUploader implements IUpload { //代理类持有目标对象类的引用 CommonUploader commonUploader; private ProxyUploader(CommonUploader commonUploader) { this.commonUploader = commonUploader; } //扩展实现 @Override public void onUpload() { commonUploader.onUpload(); } } //****运行**** public static void main(String a[]) { CommonUploader commonUploader = new CommonUploader(); //静态代理 ProxyUploader proxyUploader = new ProxyUploader(commonUploader); proxyUploader.onUpload(); } 复制代码
运行结果: 普通上传啦~
静态代理是自己写代理类,动态代理是让代码动态实现代理类:
interface IUpload { void onUpload(); } public static class CommonUploader implements IUpload { @Override public void onUpload() { System.out.println("普通上传啦~"); } } //****以上代码和静态代码一致 public static class DynamicProxyUploader implements InvocationHandler { Object object; DynamicProxyUploader(Object o) { this.object = o; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { method.invoke(object, args); return null; } } //***运行 public static void main(String a[]) { CommonUploader commonUploader = new CommonUploader(); //动态代理 IUpload iUpload = (IUpload) Proxy.newProxyInstance(commonUploader.getClass().getClassLoader(), commonUploader.getClass().getInterfaces(), new DynamicProxyUploader(commonUploader)); iUpload.onUpload(); } 复制代码
运行结果: 普通上传啦~
Proxy类位于Java源代码的java.lang.reflect下,是动态代理机制的主类,它提供了一组静态方法来为一组接口动态地生成代理类及其实例。
Thanks: