一、代理模式的引入
靜態代理舉例
特點:代理類和被代理類在編譯期間,就確定下來了。
interface ClothFactory{ void produceCloth(); } //代理類 class ProxyClothFactory implements ClothFactory{ private ClothFactory factory;//用被代理類對象進行實例化 public ProxyClothFactory(ClothFactory factory){ this.factory = factory; } @Override public void produceCloth() { System.out.println("代理工廠做一些準備工作"); factory.produceCloth(); System.out.println("代理工廠做一些后續的收尾工作"); } } //被代理類 class NikeClothFactory implements ClothFactory{ @Override public void produceCloth() { System.out.println("Nike工廠生產一批運動服"); } } public class StaticProxyTest { public static void main(String[] args) { //創建被代理類的對象 NikeClothFactory nike = new NikeClothFactory(); //創建代理類的對象 ProxyClothFactory proxyClothFactory = new ProxyClothFactory(nike); proxyClothFactory.produceCloth(); }
二、動態代理
動態代理的舉例
interface Human{ String getBelief(); void eat(String food); } //被代理類 class SuperMan implements Human{ @Override public String getBelief() { return "I believe I can fly!"; } @Override public void eat(String food) { System.out.println("我喜歡吃" + food); } } class HumanUtil{ public void method1(){ System.out.println("===================通用方法一==============================="); } public void method2(){ System.out.println("===================通用方法二==============================="); } } /* 要想實現動態代理,需要解決的問題? 問題一:如何根據加載到內存中的被代理類,動態的創建一個代理類及其對象。 問題二:當通過代理類的對象調用方法a時,如何動態的去調用被代理類中的同名方法a。 */ class ProxyFactory{ //調用此方法,返回一個代理類的對象。解決問題一 public static Object getProxyInstance(Object obj){//obj:被代理類的對象 MyInvocationHandler handler = new MyInvocationHandler(); handler.bind(obj); return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler); } } class MyInvocationHandler implements InvocationHandler{ private Object obj;//需要使用被代理類的對象進行賦值 public void bind(Object obj){ this.obj = obj; } //當我們通過代理類的對象,調用方法a時,就會自動的調用如下的方法:invoke() //將被代理類要執行的方法a的功能就聲明在invoke()中 @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HumanUtil util = new HumanUtil(); util.method1(); //method:即為代理類對象調用的方法,此方法也就作為了被代理類對象要調用的方法 //obj:被代理類的對象 Object returnValue = method.invoke(obj,args); util.method2(); //上述方法的返回值就作為當前類中的invoke()的返回值。 return returnValue; } } public class ProxyTest{ public static void main(String[] args) { SuperMan superMan = new SuperMan(); Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan); //當通過代理類對象調用方法時,會自動的調用被代理類中同名的方法 String belief = proxyInstance.getBelief(); System.out.println(belief); proxyInstance.eat("四川麻辣燙"); System.out.println("************************************************"); NikeClothFactory nikeClothFactory = new NikeClothFactory(); ClothFactory proxyClothFactory = (ClothFactory) ProxyFactory.getProxyInstance(nikeClothFactory); proxyClothFactory.produceCloth(); }
到此這篇關于Java反射的應用之動態代理深入理解的文章就介紹到這了,更多相關Java動態代理內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_49329785/article/details/120069287