代理模式是軟件開(kāi)發(fā)中常見(jiàn)的設(shè)計(jì)模式骂澄,它的目的是讓調(diào)用者不用持有具體操作者的引用,而是通過(guò)代理者去對(duì)具體操作者執(zhí)行具體的操作挣柬。
靜態(tài)代理的實(shí)現(xiàn)
操作接口:
public interface Operate {
void doSomething();
}
操作者:
public class Operator implements Operate {
@Override
public void doSomething() {
System.out.println("I'm doing something");
}
}
代理者:
public class OperationProxy implements Operate {
private Operator operator = null;
@Override
public void doSomething() {
beforeDoSomething();
if(operator == null){
operator = new Operator();
}
operator.doSomething();
afterDoSomething();
}
private void beforeDoSomething() {
System.out.println("before doing something");
}
private void afterDoSomething() {
System.out.println("after doing something");
}
}
調(diào)用者:
public class StaticProxyTest {
public static void main(String[] args) {
Operate operate = new OperationProxy();//使用OperationProxy代替Operator
operate.doSomething(); //代理者代替真實(shí)者做事情
}
}
靜態(tài)代理的局限性
可以看到潮酒,靜態(tài)代理讓調(diào)用者不用再直接持有操作者的引用,而是將一切操作交由代理者去完成邪蛔。但是靜態(tài)代理也有它的局限性:
- 如果需要增加一個(gè)需要代理的方法急黎,代理者的代碼也必須改動(dòng)進(jìn)而適配新的操作;
- 如果需要代理者代理另外一個(gè)操作者,同樣需要對(duì)代理者進(jìn)行擴(kuò)展并且更加麻煩勃教。
可能有人想到可以用策略模式和工廠模式分別解決上面兩個(gè)問(wèn)題淤击,但是,有沒(méi)有更加巧妙的方法呢故源?首先污抬,我們了解一下 Java 代碼的執(zhí)行過(guò)程。
理解 Java 代碼執(zhí)行流程
要從根本上理解動(dòng)態(tài)代理的實(shí)現(xiàn)原理绳军,得先從 Java 代碼的執(zhí)行流程說(shuō)起:
JVM 在運(yùn)行 .class 文件之前印机,首先通過(guò) ClassLoader 將 .class 文件以二進(jìn)制的形式解析并生成實(shí)例以供調(diào)用,我們的代碼執(zhí)行邏輯是在 JVM 的運(yùn)行期系統(tǒng)中進(jìn)行工作的门驾,那么射赛,我們可不可以在自己的代碼里面按照 .class 的格式生成自己的 .class 文件,進(jìn)而調(diào)用自定義的 ClassLoader 將其加載出來(lái)呢奶是?答案是肯定的楣责,這樣我們就可以動(dòng)態(tài)地創(chuàng)建一個(gè)類了。
生成自己的 .class 文件
當(dāng)然我們不用手動(dòng)去一點(diǎn)一點(diǎn)拼裝 .class 文件诫隅,目前比較常用的字節(jié)碼生成工具有 ASM 和 Javassist腐魂,根據(jù)這個(gè)思路,生成 .class 文件的過(guò)程如下:
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
public class Test {
public static void main(String[] args) throws Exception {
ClassPool pool = ClassPool.getDefault();
//創(chuàng)建 AutoGenerateClass 類
CtClass cc= pool.makeClass("com.guanpj.AutoGenerateClass");
//定義 show 方法
CtMethod method = CtNewMethod.make("public void show(){}", cc);
//插入方法代碼
method.insertBefore("System.out.println(\"I'm just test generate .class file by javassit.....\");");
cc.addMethod(method);
//保存生成的字節(jié)碼
cc.writeFile("D://temp");
}
}
生成的 .class 文件如下:
反編譯后查看內(nèi)容:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.guanpj;
public class AutoGenerateClass {
public void show() {
System.out.println("I'm just test generate .class file by javassit.....");
}
public AutoGenerateClass() {
}
}
可以看到逐纬,javassit 生成的類中蛔屹,除了 show() 方法之外還默認(rèn)生成了一個(gè)無(wú)參的構(gòu)造方法。
自定義類加載器加載
為了能夠讓自定的類被加載出來(lái)豁生,我們自定義了一個(gè)類加載器來(lái)加載指定的 .class 文件:
public class CustomClassLoader extends ClassLoader {
public CustomClassLoader() {
}
protected Class<?> findClass(String className) {
String path = "D://temp//" + className.replace(".","http://") + ".class";
byte[] classData = getClassData(path);
return defineClass(className, classData, 0, classData.length);
}
private byte[] getClassData(String path) {
try {
InputStream ins = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bufferSize = 4096;
byte[] buffer = new byte[bufferSize];
int bytesNumRead = 0;
while ((bytesNumRead = ins.read(buffer)) != -1) {
baos.write(buffer, 0, bytesNumRead);
}
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
接著兔毒,用 ClassLoader 加載剛才生成的 .class 文件:
public class TestLoadClass {
public static void main(String[] args) throws Exception {
CustomClassLoader classLoader = new CustomClassLoader();
Class clazz = classLoader.findClass("com.guanpj.AutoGenerateClass");
Object object = clazz.newInstance();
Method showMethod = clazz.getMethod("show", null);
showMethod.invoke(object, null);
}
}
后臺(tái)輸出如下:
成功執(zhí)行了 show 方法!
利用 JDK 中的 Proxy 類進(jìn)行動(dòng)態(tài)代理
使用動(dòng)態(tài)代理的初衷是簡(jiǎn)化代碼甸箱,不管是 ASM 還是 Javassist育叁,在進(jìn)行動(dòng)態(tài)代理的時(shí)候操作還是不夠簡(jiǎn)便,這也違背了我們的初衷芍殖。我們來(lái)看一下怎么 InvocationHandler 怎么做:
InvocationHandler:
public class InvocationHandlerImpl implements InvocationHandler {
Operate operate;
//注入操作者對(duì)象
public InvocationHandlerImpl(Operate operate) {
this.operate = operate;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before calling method: " + method.getName());
//調(diào)用操縱者的具體操作方法
method.invoke(operate, args);
System.out.println("after calling method: " + method.getName());
return null;
}
}
調(diào)用者:
public class DynamicProxyTest {
public static void main(String[] args) {
//實(shí)例化操作者
Operate operate = new Operator();
//將操作者對(duì)象進(jìn)行注入
InvocationHandlerImpl handler = new InvocationHandlerImpl(operate);
//生成代理對(duì)象
Operate operationProxy = (Operate) Proxy.newProxyInstance(operate.getClass().getClassLoader(),
operate.getClass().getInterfaces(), handler);
//調(diào)用操作方法
operationProxy.doSomething();
}
}
跟靜態(tài)代理不同的是豪嗽,動(dòng)態(tài)代理的過(guò)程主要分為三個(gè)步驟
- 將操作者對(duì)象注入 InvocationHandlerImpl 類中。
- 將 InvocationHandlerImpl 對(duì)象注入 Proxy 類中并返回代理者對(duì)象豌骏,并在 invoke 方法中進(jìn)行額外的操作
- 調(diào)用代理對(duì)象的操作方法
利用 CGLIB 進(jìn)行動(dòng)態(tài)代理
用 Proxy 類生成代理類的方法為 newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) 龟梦,第二個(gè)參數(shù)是操作者的接口數(shù)組,意味著只能代理它實(shí)現(xiàn)的接口里的方法窃躲,對(duì)于本來(lái)在操作者類中定義的方法表示無(wú)能為力计贰,CGLIB(Code Generation Library) 解決了這個(gè)問(wèn)題。
MethodInterceptorImpl:
public class MethodInterceptorImpl implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("before calling method:" + method.getName());
proxy.invokeSuper(obj, args);
System.out.println("after calling method:" + method.getName());
return null;
}
}
調(diào)用者:
public class ProxyTest {
public static void main(String[] args) {
Operator operator = new Operator();
MethodInterceptorImpl methodInterceptorImpl = new MethodInterceptorImpl();
//初始化加強(qiáng)器對(duì)象
Enhancer enhancer = new Enhancer();
//設(shè)置代理類
enhancer.setSuperclass(operator.getClass());
//設(shè)置代理回調(diào)
enhancer.setCallback(methodInterceptorImpl);
//創(chuàng)建代理對(duì)象
Operator operationProxy = (Operator) enhancer.create();
//調(diào)用操作方法
operationProxy.doSomething();
}
}
使用 CGLIB 進(jìn)行動(dòng)態(tài)代理的過(guò)程分為四個(gè)步驟:
- 使用 MethodInterceptorImpl 實(shí)現(xiàn) MethodInterceptor 接口蒂窒,并在 intercept 方法中進(jìn)行額外的操作
- 創(chuàng)建增強(qiáng)器 Enhance 并設(shè)置被代理的操作類
- 生成代理類
- 調(diào)用代理對(duì)象的操作方法
總結(jié)
無(wú)論是靜態(tài)代理還是動(dòng)態(tài)代理躁倒,都能一定程度地解決我們的問(wèn)題荞怒,在開(kāi)發(fā)過(guò)程中可以根據(jù)實(shí)際情況選擇合適的方案⊙肀總之褐桌,沒(méi)有好不好的方案,只有適不適合自己項(xiàng)目的方案福贞,我們應(yīng)該深入研究和理解方案背后的原理撩嚼,以便能夠應(yīng)對(duì)開(kāi)發(fā)過(guò)程中產(chǎn)生的變數(shù)。
文章中的代碼已經(jīng)上傳至我的 Github挖帘,如果你對(duì)文章內(nèi)容有不同意見(jiàn)完丽,歡迎留言,我們一同探討拇舀。