设计模式6---代理模式(Proxy Pattern)
代理設計模式
定義:為其他對象提供一種代理以控制對這個對象的訪問。
1.? 靜態代理
靜態代理在使用時,需要定義接口或者父類,被代理對象與代理對象都實現相同的接口或者是繼承相同父類。
接口:IUserDao.java
/*** 接口*/ public interface IUserDao {void save(); }?
目標對象:UserDao.java
/*** 目標對象(接口的實現類)*/ public class UserDao implements IUserDao {public void save() {System.out.println("----已經保存數據!----");} }?
代理對象:UserDaoProxy.java
/*** 代理對象,靜態代理*/ public class UserDaoProxy implements IUserDao{//接收保存目標對象private IUserDao target;public UserDaoProxy(IUserDao target){this.target=target;}public void save() {System.out.println("開始事務...");target.save();//執行目標對象的方法System.out.println("提交事務...");} }?
測試類:Test.java
/*** 測試類*/ public class Test {public static void main(String[] args) {//目標對象UserDao target = new UserDao();//代理對象,把目標對象傳給代理對象,建立代理關系UserDaoProxy proxy = new UserDaoProxy(target);proxy.save();//執行代理方法 }}?
靜態代理總結:
1.可以做到在不修改目標對象的功能前提下,對目標功能擴展.
2.缺點:因為代理對象需要與目標對象實現一樣的接口, 所以會有很多代理類,類太多。同時,一旦接口增加方法,目標對象與代理對象都要維護。
如何解決靜態代理中的缺點,那就是動態代理方式。
2. 動態代理使用
Java動態代理機制以巧妙的方式實現了代理模式的設計理念。?先看一下動態代理的使用:?
package dynamic.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 實現自己的InvocationHandler * */ public class MInvocationHandler implements InvocationHandler { // 目標對象 private Object target; /** * 構造方法 * @param target 目標對象 */ public MInvocationHandler(Object target) { super(); this.target = target; } /** * 執行目標對象的方法 */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 在目標對象的方法執行之前簡單的打印一下 System.out.println("------------------before------------------"); // 執行目標對象的方法 Object result = method.invoke(target, args); // 在目標對象的方法執行之后簡單的打印一下 System.out.println("-------------------after------------------"); return result; } /** * 獲取目標對象的代理對象 * @return 代理對象 */ public Object getProxy() { return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), target.getClass().getInterfaces(), this); } }package dynamic.proxy; /** * 目標對象實現的接口,用JDK來生成代理對象一定要實現一個接口 * */ public interface UserService { /** * 目標方法 */ public abstract void add(); }
package dynamic.proxy; /** * 目標對象 * */ public class UserServiceImpl implements UserService { /* (non-Javadoc) * @see dynamic.proxy.UserService#add() */ public void add() { System.out.println("----------add-----------"); } }
package dynamic.proxy; import org.junit.Test; /** * 動態代理測試類 */ public class ProxyTest { @Test public void testProxy() throws Throwable { // 實例化目標對象 UserService userService = new UserServiceImpl(); // 實例化InvocationHandler MInvocationHandler invocationHandler = new MInvocationHandler(userService); // 根據目標對象生成代理對象 UserService proxy = (UserService) invocationHandler.getProxy(); // 調用代理對象的方法 proxy.add(); } }
執行結果如下:?
------------------before------------------?
--------------------add---------------?
-------------------after------------------?
? ? ? ?用起來是很簡單吧,其實這里基本上就是AOP的一個簡單實現了,在目標對象的方法執行之前和執行之后進行了增強。
Spring的AOP實現其實也是用了Proxy和InvocationHandler這兩個東西的。?使用比較簡單,看一下JDK是怎樣生成代理對象的,即Proxy類的靜態方法newProxyInstance。
3、動態代理源碼解析
/** * loader:類加載器 * interfaces:目標對象實現的接口 * h:InvocationHandler的實現類 */ public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException { if (h == null) { throw new NullPointerException(); } /* * Look up or generate the designated proxy class. */ Class cl = getProxyClass(loader, interfaces); /* * Invoke its constructor with the designated invocation handler. */ try { // 調用代理對象的構造方法(也就是$Proxy0(InvocationHandler h)) Constructor cons = cl.getConstructor(constructorParams); // 生成代理類的實例并把MyInvocationHandler的實例傳給它的構造方法 return (Object) cons.newInstance(new Object[] { h }); } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); } catch (IllegalAccessException e) { throw new InternalError(e.toString()); } catch (InstantiationException e) { throw new InternalError(e.toString()); } catch (InvocationTargetException e) { throw new InternalError(e.toString()); } }? ?我們再進去getProxyClass方法看一下
public static Class<?> getProxyClass(ClassLoader loader, Class<?>... interfaces) throws IllegalArgumentException { // 如果目標類實現的接口數大于65535個則拋出異常(我XX,誰會寫這么NB的代碼啊?) if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } // 聲明代理對象所代表的Class對象(有點拗口) Class proxyClass = null; String[] interfaceNames = new String[interfaces.length]; Set interfaceSet = new HashSet(); // for detecting duplicates // 遍歷目標類所實現的接口 for (int i = 0; i < interfaces.length; i++) { // 拿到目標類實現的接口的名稱 String interfaceName = interfaces[i].getName(); Class interfaceClass = null; try { // 加載目標類實現的接口到內存中 interfaceClass = Class.forName(interfaceName, false, loader); } catch (ClassNotFoundException e) { } if (interfaceClass != interfaces[i]) { throw new IllegalArgumentException( interfaces[i] + " is not visible from class loader"); } // 中間省略了一些無關緊要的代碼 ....... // 把目標類實現的接口代表的Class對象放到Set中 interfaceSet.add(interfaceClass); interfaceNames[i] = interfaceName; } // 把目標類實現的接口名稱作為緩存(Map)中的key Object key = Arrays.asList(interfaceNames); Map cache; synchronized (loaderToCache) { // 從緩存中獲取cache cache = (Map) loaderToCache.get(loader); if (cache == null) { // 如果獲取不到,則新建地個HashMap實例 cache = new HashMap(); // 把HashMap實例和當前加載器放到緩存中 loaderToCache.put(loader, cache); } } synchronized (cache) { do { // 根據接口的名稱從緩存中獲取對象 Object value = cache.get(key); if (value instanceof Reference) { proxyClass = (Class) ((Reference) value).get(); } if (proxyClass != null) { // 如果代理對象的Class實例已經存在,則直接返回 return proxyClass; } else if (value == pendingGenerationMarker) { try { cache.wait(); } catch (InterruptedException e) { } continue; } else { cache.put(key, pendingGenerationMarker); break; } } while (true); } try { // 中間省略了一些代碼 ....... // 這里就是動態生成代理對象的最關鍵的地方 byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces); try { // 根據代理類的字節碼生成代理類的實例 proxyClass = defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); } catch (ClassFormatError e) { throw new IllegalArgumentException(e.toString()); } } // add to set of all generated proxy classes, for isProxyClass proxyClasses.put(proxyClass, null); } // 中間省略了一些代碼 ....... return proxyClass; }進去ProxyGenerator類的靜態方法generateProxyClass,這里是真正生成代理類class字節碼的地方。?
public static byte[] generateProxyClass(final String name, Class[] interfaces) { ProxyGenerator gen = new ProxyGenerator(name, interfaces); // 這里動態生成代理類的字節碼,由于比較復雜就不進去看了 final byte[] classFile = gen.generateClassFile(); // 如果saveGeneratedFiles的值為true,則會把所生成的代理類的字節碼保存到硬盤上 if (saveGeneratedFiles) { java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() { public Void run() { try { FileOutputStream file = new FileOutputStream(dotToSlash(name) + ".class"); file.write(classFile); file.close(); return null; } catch (IOException e) { throw new InternalError( "I/O exception saving generated file: " + e); } } }); } // 返回代理類的字節碼 return classFile; }現在,JDK是怎樣動態生成代理類的字節的原理已經一目了然了。?
再來解決另外一個問題“由誰來調用InvocationHandler的invoke方法“。要解決這個問題就要看一下JDK到底為我們生成了一個什么東西。用以下代碼可以獲取到JDK為我們生成的字節碼并寫到硬盤中。?
1 package dynamic.proxy; 2 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 6 import sun.misc.ProxyGenerator; 7 8 /** 9 * 代理類的生成工具10 *
11 * 12 */ 13 public class ProxyGeneratorUtils { 14 15 /** 16 * 把代理類的字節碼寫到硬盤上 17 * @param path 保存路徑 18 */ 19 public static void writeProxyClassToHardDisk(String path) { 20 // 第一種方法,這種方式在剛才分析ProxyGenerator時已經知道了 21 // System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", true); 22 23 // 第二種方法 24 25 // 獲取代理類的字節碼 26 byte[] classFile = ProxyGenerator.generateProxyClass("$Proxy11", UserServiceImpl.class.getInterfaces()); 27 28 FileOutputStream out = null; 29 30 try { 31 out = new FileOutputStream(path); 32 out.write(classFile); 33 out.flush(); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } finally { 37 try { 38 out.close(); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } 42 } 43 } 44 } 45
46 package dynamic.proxy; 47 48 import org.junit.Test; 49 50 /** 51 * 動態代理測試類 52 * 53 * 54 * 55 */ 56 public class ProxyTest { 57 58 @Test 59 public void testProxy() throws Throwable { 60 // 實例化目標對象 61 UserService userService = new UserServiceImpl(); 62 63 // 實例化InvocationHandler 64 MyInvocationHandler invocationHandler = new MyInvocationHandler(userService); 65 66 // 根據目標對象生成代理對象 67 UserService proxy = (UserService) invocationHandler.getProxy(); 68 69 // 調用代理對象的方法 70 proxy.add(); 71 72 } 73 74 @Test 75 public void testGenerateProxyClass() { 76 ProxyGeneratorUtils.writeProxyClassToHardDisk("F:/$Proxy11.class"); 77 } 78 }
通過以上代碼,就可以在F盤上生成一個$Proxy.class文件了,現在用反編譯工具來看一下這個class文件里面的內容。?
5 import dynamic.proxy.UserService; 6 import java.lang.reflect.*; 7 8 public final class $Proxy11 extends Proxy implements UserService 10 { 11 12 // 構造方法,參數就是剛才傳過來的MyInvocationHandler類的實例 13 public $Proxy11(InvocationHandler invocationhandler) 14 { 15 super(invocationhandler); 16 } 17 18 public final boolean equals(Object obj) 19 { 20 try 21 { 22 return ((Boolean)super.h.invoke(this, m1, new Object[] { 23 obj 24 })).booleanValue(); 25 } 26 catch(Error _ex) { } 27 catch(Throwable throwable) 28 { 29 throw new UndeclaredThrowableException(throwable); 30 } 31 } 32 33 /** 34 * 這個方法是關鍵部分 35 */ 36 public final void add() 37 { 38 try 39 { 40 // 實際上就是調用MyInvocationHandler的public Object invoke(Object proxy, Method method, Object[] args)方法,第二個問題就解決了 41 super.h.invoke(this, m3, null); 42 return; 43 } 44 catch(Error _ex) { } 45 catch(Throwable throwable) 46 { 47 throw new UndeclaredThrowableException(throwable); 48 } 49 } 50 51 public final int hashCode() 52 { 53 try 54 { 55 return ((Integer)super.h.invoke(this, m0, null)).intValue(); 56 } 57 catch(Error _ex) { } 58 catch(Throwable throwable) 59 { 60 throw new UndeclaredThrowableException(throwable); 61 } 62 } 63 64 public final String toString() 65 { 66 try 67 { 68 return (String)super.h.invoke(this, m2, null); 69 } 70 catch(Error _ex) { } 71 catch(Throwable throwable) 72 { 73 throw new UndeclaredThrowableException(throwable); 74 } 75 } 76 77 private static Method m1; 78 private static Method m3; 79 private static Method m0; 80 private static Method m2; 81 82 // 在靜態代碼塊中獲取了4個方法:Object中的equals方法、UserService中的add方法、Object中的hashCode方法、Object中toString方法 83 static 84 { 85 try 86 { 87 m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { 88 Class.forName("java.lang.Object") 89 }); 90 m3 = Class.forName("dynamic.proxy.UserService").getMethod("add", new Class[0]); 91 m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]); 92 m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]); 93 } 94 catch(NoSuchMethodException nosuchmethodexception) 95 { 96 throw new NoSuchMethodError(nosuchmethodexception.getMessage()); 97 } 98 catch(ClassNotFoundException classnotfoundexception) 99 { 100 throw new NoClassDefFoundError(classnotfoundexception.getMessage()); 101 } 102 } 103 } 104
?
4、動態代理源碼解析
類Proxy的代碼實現?Proxy的主要靜態變量
// 映射表:用于維護類裝載器對象到其對應的代理類緩存 private static Map loaderToCache = new WeakHashMap(); // 標記:用于標記一個動態代理類正在被創建中 private static Object pendingGenerationMarker = new Object(); // 同步表:記錄已經被創建的動態代理類類型,主要被方法 isProxyClass 進行相關的判斷 private static Map proxyClasses = Collections.synchronizedMap(new WeakHashMap()); // 關聯的調用處理器引用 protected InvocationHandler h;Proxy的構造方法
// 由于 Proxy 內部從不直接調用構造函數,所以 private 類型意味著禁止任何調用 private Proxy() {} // 由于 Proxy 內部從不直接調用構造函數,所以 protected 意味著只有子類可以調用 protected Proxy(InvocationHandler h) {this.h = h;}Proxy靜態方法newProxyInstance
public static Object newProxyInstance(ClassLoader loader, Class<?>[]interfaces,InvocationHandler h) throws IllegalArgumentException { // 檢查 h 不為空,否則拋異常if (h == null) { throw new NullPointerException(); } // 獲得與指定類裝載器和一組接口相關的代理類類型對象Class cl = getProxyClass(loader, interfaces); // 通過反射獲取構造函數對象并生成代理類實例try { Constructor cons = cl.getConstructor(constructorParams); return (Object) cons.newInstance(new Object[] { h }); } catch (NoSuchMethodException e) { throw new InternalError(e.toString()); } catch (IllegalAccessException e) { throw new InternalError(e.toString()); } catch (InstantiationException e) { throw new InternalError(e.toString()); } catch (InvocationTargetException e) { throw new InternalError(e.toString()); } }類Proxy的getProxyClass方法調用ProxyGenerator的?generateProxyClass方法產生ProxySubject.class的二進制數據:
public static byte[] generateProxyClass(final String name, Class[] interfaces)我們可以import sun.misc.ProxyGenerator,調用?generateProxyClass方法產生binary data,然后寫入文件,最后通過反編譯工具來查看內部實現原理。 反編譯后的ProxySubject.java?Proxy靜態方法newProxyInstance
import java.lang.reflect.*; public final class ProxySubject extends Proxy implements Subject { private static Method m1; private static Method m0; private static Method m3; private static Method m2; public ProxySubject(InvocationHandler invocationhandler) { super(invocationhandler); } public final boolean equals(Object obj) { try { return ((Boolean)super.h.invoke(this, m1, new Object[] { obj })).booleanValue(); } catch(Error _ex) { } catch(Throwable throwable) { throw new UndeclaredThrowableException(throwable); } } public final int hashCode() { try { return ((Integer)super.h.invoke(this, m0, null)).intValue(); } catch(Error _ex) { } catch(Throwable throwable) { throw new UndeclaredThrowableException(throwable); } } public final void doSomething() { try { super.h.invoke(this, m3, null); return; } catch(Error _ex) { } catch(Throwable throwable) { throw new UndeclaredThrowableException(throwable); } } public final String toString() { try { return (String)super.h.invoke(this, m2, null); } catch(Error _ex) { } catch(Throwable throwable) { throw new UndeclaredThrowableException(throwable); } } static { try { m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") }); m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]); m3 = Class.forName("Subject").getMethod("doSomething", new Class[0]); m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]); } catch(NoSuchMethodException nosuchmethodexception) { throw new NoSuchMethodError(nosuchmethodexception.getMessage()); } catch(ClassNotFoundException classnotfoundexception) { throw new NoClassDefFoundError(classnotfoundexception.getMessage()); } } }ProxyGenerator內部是如何生成class二進制數據,可以參考源代碼。
private byte[] generateClassFile() { /* * Record that proxy methods are needed for the hashCode, equals, * and toString methods of java.lang.Object. This is done before * the methods from the proxy interfaces so that the methods from * java.lang.Object take precedence over duplicate methods in the * proxy interfaces. */ addProxyMethod(hashCodeMethod, Object.class); addProxyMethod(equalsMethod, Object.class); addProxyMethod(toStringMethod, Object.class); /* * Now record all of the methods from the proxy interfaces, giving * earlier interfaces precedence over later ones with duplicate * methods. */ for (int i = 0; i < interfaces.length; i++) { Method[] methods = interfaces[i].getMethods(); for (int j = 0; j < methods.length; j++) { addProxyMethod(methods[j], interfaces[i]); } } /* * For each set of proxy methods with the same signature, * verify that the methods' return types are compatible. */ for (List<ProxyMethod> sigmethods : proxyMethods.values()) { checkReturnTypes(sigmethods); } /* ============================================================ * Step 2: Assemble FieldInfo and MethodInfo structs for all of * fields and methods in the class we are generating. */ try { methods.add(generateConstructor()); for (List<ProxyMethod> sigmethods : proxyMethods.values()) { for (ProxyMethod pm : sigmethods) { // add static field for method's Method object fields.add(new FieldInfo(pm.methodFieldName, "Ljava/lang/reflect/Method;", ACC_PRIVATE | ACC_STATIC)); // generate code for proxy method and add it methods.add(pm.generateMethod()); } } methods.add(generateStaticInitializer()); } catch (IOException e) { throw new InternalError("unexpected I/O Exception"); } /* ============================================================ * Step 3: Write the final class file. */ /* * Make sure that constant pool indexes are reserved for the * following items before starting to write the final class file. */ cp.getClass(dotToSlash(className)); cp.getClass(superclassName); for (int i = 0; i < interfaces.length; i++) { cp.getClass(dotToSlash(interfaces[i].getName())); } /* * Disallow new constant pool additions beyond this point, since * we are about to write the final constant pool table. */ cp.setReadOnly(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream dout = new DataOutputStream(bout); try { /* * Write all the items of the "ClassFile" structure. * See JVMS section 4.1. */ // u4 magic; dout.writeInt(0xCAFEBABE); // u2 minor_version; dout.writeShort(CLASSFILE_MINOR_VERSION); // u2 major_version; dout.writeShort(CLASSFILE_MAJOR_VERSION); cp.write(dout); // (write constant pool) // u2 access_flags; dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER); // u2 this_class; dout.writeShort(cp.getClass(dotToSlash(className))); // u2 super_class; dout.writeShort(cp.getClass(superclassName)); // u2 interfaces_count; dout.writeShort(interfaces.length); // u2 interfaces[interfaces_count]; for (int i = 0; i < interfaces.length; i++) { dout.writeShort(cp.getClass( dotToSlash(interfaces[i].getName()))); } // u2 fields_count; dout.writeShort(fields.size()); // field_info fields[fields_count]; for (FieldInfo f : fields) { f.write(dout); } // u2 methods_count; dout.writeShort(methods.size()); // method_info methods[methods_count]; for (MethodInfo m : methods) { m.write(dout); } // u2 attributes_count; dout.writeShort(0); // (no ClassFile attributes for proxy classes) } catch (IOException e) { throw new InternalError("unexpected I/O Exception"); } return bout.toByteArray();總結
一個典型的動態代理創建對象過程可分為以下四個步驟:
1、通過實現InvocationHandler接口創建自己的調用處理器 IvocationHandler handler = new InvocationHandlerImpl(...);
2、通過為Proxy類指定ClassLoader對象和一組interface創建動態代理類;
Class clazz = Proxy.getProxyClass(classLoader,new Class[]{...});
3、通過反射機制獲取動態代理類的構造函數,其參數類型是調用處理器接口類型;
Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.class});
4、通過構造函數創建代理類實例,此時需將調用處理器對象作為參數被傳入,
Interface Proxy = (Interface)constructor.newInstance(new Object[] (handler));
為了簡化對象創建過程,Proxy類中的newInstance方法封裝了2~4,只需兩步即可完成代理對象的創建。生成的ProxySubject繼承Proxy類實現Subject接口,實現的Subject的方法實際調用處理器的invoke方法,而invoke方法利用反射調用的是被代理對象的的方法(Object result=method.invoke(proxied,args))。
5. 美中不足
誠然,Proxy已經設計得非常優美,但是還是有一點點小小的遺憾之處,那就是它始終無法擺脫僅支持interface代理的桎梏,因為它的設計注定了這個遺憾。回想一下那些動態生成的代理類的繼承關系圖,它們已經注定有一個共同的父類叫Proxy。Java的繼承機制注定了這些動態代理類們無法實現對class的動態代理,原因是多繼承在Java中本質上就行不通。有很多條理由,人們可以否定對 class代理的必要性,但是同樣有一些理由,相信支持class動態代理會更美好。接口和類的劃分,本就不是很明顯,只是到了Java中才變得如此的細化。如果只從方法的聲明及是否被定義來考量,有一種兩者的混合體,它的名字叫抽象類。實現對抽象類的動態代理,相信也有其內在的價值。此外,還有一些歷史遺留的類,它們將因為沒有實現任何接口而從此與動態代理永世無緣。如此種種,不得不說是一個小小的遺憾。但是,不完美并不等于不偉大,偉大是一種本質,Java動態代理就是佐例。
?
參考資料
1、JDK動態代理實現原理
2、Java動態代理機制分析及擴展
轉載于:https://www.cnblogs.com/linghu-java/p/5711450.html
總結
以上是生活随笔為你收集整理的设计模式6---代理模式(Proxy Pattern)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mmap使用说明
- 下一篇: CoreData / MagicalRe