代理模式的作用是控制和管理物件的訪問許可權;它的優點是:想要找代理的物件,可以不用每次都自己實現某個功能,可以把某個方法的呼叫許可權,交給代理類來完成。一般分為靜態代理和動態代理。要實現代理模式,代理類和目標類需要實現同樣的介面。 這個以上傳業務舉例:
靜態代理
//我們定一個介面
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 args[]) {
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: