代理模式的定義:爲其餘對象提供一種代理以控制對這個對象的訪問。java
代理模式是23種經常使用的面向對象軟件的設計模式之一,具體又分爲靜態代理、動態代理。node
思考抽象問題最好的辦法就是具體化!git
好比咱們須要爲一個業務方法在執行先後記錄日誌,爲了達到解耦的目的,咱們能夠再新建一個類並定義一個新的業務方法,該方法既能夠調用原業務方法,又能夠在調用先後進行日誌處理,例如:程序員
CarProxy.class public void move() { System.out.println("日誌開始記錄...."); new Car().move(); System.out.println("日誌記錄完成...."); }
代理模式的應用不少,好比Spring容器的延遲加載,AOP加強處理等。後端
靜態代理是由程序員建立或工具生成代理類的源碼,再編譯代理類。設計模式
所謂靜態也就是在程序運行前就已經存在代理類的字節碼文件,代理類和委託類的關係在運行前就肯定了。app
一句話,本身手寫代理類就是靜態代理。ide
目標對象:定義一個普通方法函數
public class Car { public void move() { System.out.println("1.汽車開始跑步"); System.out.println("2.汽車跑到了終點"); } }
代理對象:主要做用是繼承目標對象,進行加強處理,並使用關鍵字super調用父類方法。工具
public class CarProxy extends Car { @Override public void move() { System.out.println("日誌開始記錄...."); super.move(); System.out.println("日誌記錄完成...."); } }
測試方法:其實是調用代理對象的move()方法。
public static void main(String[] args) { Car car = new CarProxy(); car.move(); }
共同接口:定義一個普通的接口方法
public interface Moveable { void move(); }
目標對象:實現該接口方法。
public class Car implements Moveable { @Override public void move() { System.out.println("汽車行駛中...."); } }
代理對象:調用目標對象的方法,並在調用先後進行加強處理。
public class CarProxy implements Moveable{ private Moveable move; @Override public void move() { if(move==null){ move = new Car(); } System.out.println("開始記錄日誌:"); move.move(); System.out.println("記錄日誌結束!"); } }
測試方法:其實是調用代理對象的move()方法。
public static void main(String[] args) throws Exception { Moveable m =new CarProxy(); m.move(); }
優勢:
業務類只須要關注業務邏輯自己,保證了業務類的重用性。這是代理模式的共有優勢。
缺點:
1)代理對象的一個接口只服務於一種類型的對象,若是要代理的類型不少,勢必要爲每一種類型的方法都進行代理,靜態代理在程序規模稍大時就沒法勝任了。
2)若是接口增長一個方法,除了全部實現類須要實現這個方法外,全部代理類也須要實現此方法。顯而易見,增長了代碼維護的複雜度。
動態代理是在實現階段不用關心代理類,而在運行階段才指定哪個對象。
動態代理類的源碼是在程序運行期間由JVM根據反射等機制動態的生成 。
簡單來講,動態代理就是交給程序去自動生成代理類。
JDK動態代理實現步驟:
共同接口
public interface Moveable { String move(); }
目標對象:正常實現接口方法
public class Car implements Moveable { @Override public String move() { return "汽車行駛中"; } }
對目標對象的加強處理:
public class LogHandler implements InvocationHandler{ private Object target; public LogHandler(Object object){ super(); this.target = object; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //加強處理 Object o = method.invoke(target,args); //加強處理 return o; } }
實現InvocationHandler接口步驟:
定義含參構造方法,該參數爲要代理的實例對象,目的是用於執行method.invoke()方法(也就是執行目標方法)
實現接口的invoke()方法,該方法用於對目標方法的加強處理,好比記錄日誌等。該方法的返回值就是代理對象執行目標方法的返回值。具體參數:
proxy 動態生成的代理對象
method 目標方法的實例
args 目標方法的參數
測試方法:
public static void main(String[] args) { Moveable move = (Moveable) Proxy.newProxyInstance(Car.class.getClassLoader(), Car.class.getInterfaces(), new LogHandler(new Car())); System.out.println("代理對象:"+move.getClass().getName()); System.out.println("執行方法:"+move.move()); }
經過調用Proxy.newProxyInstance方法生成代理對象,具體參數有:
打印結果
代理對象:com.sun.proxy.$Proxy0 執行方法:汽車行駛中
值得一提的是,JDK動態代理針對每一個代理對象都會有一個關聯的調用處理程序,即實現InvocationHandler接口。當在代理對象上調用目標方法時,將對方法調用進行編碼並將其分配給其實現 InvocationHandler 接口的 invoke 方法。
JDK的動態代理只能代理實現了接口的類, 沒有實現接口的類不能實現動態代理。
引用cglib的依賴包
<dependency> <groupId>cglib</groupId> <artifactId>cglib-nodep</artifactId> <version>2.2</version> </dependency>
爲了方便思考它的原理,我把執行步驟按順序寫下
public static void main(String[] args) { Enhancer enhancer = new Enhancer(); //設置父類,被代理類(這裏是Car.class) enhancer.setSuperclass(Car.class); //設置回調函數 enhancer.setCallback(new MethodInterceptor() { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { //加強處理... Object o= proxy.invokeSuper(obj, args);//代理類調用父類的方法 //加強處理... return o; } }); //建立代理類並使用回調(用父類Car去引用) Car car = (Car) enhancer.create(); //執行目標方法 System.out.println(car.move()); }
實現MethodInterceptor接口的intercept方法後,全部生成的代理方法都調用這個方法。
intercept方法的具體參數有
該方法的返回值就是目標方法的返回值。
從上面能夠看到JDK動態代理的核心代碼在於Proxy.newProxyInstance方法。
Moveable m = (Moveable)Proxy.newProxyInstance(Car.class,new InvocationHandler());
生產代理對象類,核心類!難點,思路都在這裏~
public class Proxy { /** * 生產代理對象 * @param clazz * @param h * @return * @throws Exception */ public static Object newProxyInstance(Class clazz,InvocationHandler h) throws Exception{ //代理類類名 String cname = clazz.getName().substring(clazz.getName().lastIndexOf(".")+1) + "$Proxy0"; //手寫代理類源碼 StringBuilder source = getSource(clazz, h, cname); //產生代理類的java文件 String filename = Thread.currentThread().getContextClassLoader().getResource("").getPath() + clazz.getPackage().getName().replaceAll("\\.", "/") +"/"+cname+".java"; System.out.println(filename); //把源碼寫入到文件中 File file = new File(filename); FileUtil.writeStringToFile(file, source.toString()); //編譯 //拿到編譯器 JavaCompiler complier = ToolProvider.getSystemJavaCompiler(); //文件管理者 StandardJavaFileManager fileMgr = complier.getStandardFileManager(null, null, null); //獲取文件 Iterable units = fileMgr.getJavaFileObjects(filename); //編譯任務 CompilationTask t = complier.getTask(null, fileMgr, null, null, null, units); //進行編譯 t.call(); fileMgr.close(); //load 到內存 ClassLoader cl = ClassLoader.getSystemClassLoader(); Class<?> c = cl.loadClass(clazz.getPackage().getName() + "."+cname); //獲取構造函數Constructor Constructor<?> ctr = c.getConstructor(h.getClass()); return ctr.newInstance(h); } /** * 手寫代理類源碼 * @param clazz * @param h * @param cname * @return */ private static StringBuilder getSource(Class clazz, InvocationHandler h, String cname) { //調用處理接口 String handler = h.getClass().getName(); //換行符號 String line = "\r\n"; String space = " "; //代理類源碼 StringBuilder source = new StringBuilder(); //包聲明 source.append("package" + space + clazz.getPackage().getName() + ";").append(line); //獲取類的名稱 source.append(Modifier.toString(clazz.getModifiers()) + space + "class" + space + cname + space); //繼承接口 source.append("implements" + space); Class[] interfaces = clazz.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { source.append(interfaces[i].getName()); if (i != interfaces.length - 1) { source.append(","); } } source.append("{").append(line); //聲明變量 source.append("private " + handler + " h;").append(line); //構造方法 source.append("public " + cname + "(" + handler + " h){").append(line); source.append("this.h=h;").append(line).append("}").append(line); //實現全部方法 Method[] methods = clazz.getDeclaredMethods(); for (Method method : methods) { //獲取方法返回類型 Class returnType = method.getReturnType(); //獲取方法上的全部註釋 Annotation[] annotations = method.getDeclaredAnnotations(); for (Annotation annotation : annotations) { //打印註釋類型 source.append("@" + annotation.annotationType().getName()).append(line); } //打印方法聲明 source.append(Modifier.toString(method.getModifiers()) + " " + returnType.getName() + " " + method.getName() + "("); //獲取方法的全部參數 Parameter[] parameters = method.getParameters(); //參數字符串 StringBuilder args = new StringBuilder(); for (int i = 0; i < parameters.length; i++) { //參數的類型,形參(全是arg123..) source.append(parameters[i].getType().getName() + " " + parameters[i].getName()); args.append(parameters[i].getName()); if (i != parameters.length - 1) { source.append(","); args.append(","); } } source.append("){").append(line); //方法邏輯 source.append("Object obj=null; \n try {").append(line); source.append("Class[] args = new Class[]{" + args + "};").append(line); source.append(Method.class.getName()+" method = " + clazz.getName() + ".class.getMethod(\"" + method.getName() + "\",args);").append(line); source.append("obj = h.invoke(this,method,args);").append(line); source.append("} catch (Exception e) {\n" + "e.printStackTrace();\n" + "}catch (Throwable throwable) {\n" + "throwable.printStackTrace();\n" + "}").append(line); //方法結束 source.append("return (obj!=null)?("+returnType.getName()+")obj:null;\n}").append(line); } //類結束 source.append("}"); return source; } }
單元測試
public static void main(String[] args) throws Exception { Moveable m = (Moveable) Proxy.newProxyInstance(Car.class, new TimeHandler(new Car())); String s = m.move(); System.out.println(s); }
測試結果
/D:/IDEA/workSpace/myJdkProxy/target/classes/cn/zyzpp/client/Car$Proxy0.java 開始記錄時間 汽車行駛中.... 耗時:481毫秒! success
我只測試了部分,有bug在所不免啦~~~!項目地址:Gitee
本文已受權「後端技術精選」發佈。