Java動(dòng)態(tài)代理的作用

先來看靜態(tài)代理模式代碼:

package test;

public interface Subject {   
  public void doSomething();   
}
package test;

public class RealSubject implements Subject   
{   
  public void doSomething() {   
    System.out.println( "call doSomething()" );   
  }   
}  
package test;

public class SubjectProxy implements Subject {
  Subject subimpl = new RealSubject();
  public void doSomething() {
     subimpl.doSomething();
  }
}
package test;

public class TestProxy 
{
   public static void main(String args[])
   {
       Subject sub = new SubjectProxy();
       sub.doSomething();
   }
}

剛開始我會(huì)覺得SubjectProxy定義出來純屬多余,直接實(shí)例化實(shí)現(xiàn)類完成操作不就結(jié)了嗎?后來隨著業(yè)務(wù)龐大,你就會(huì)知道,實(shí)現(xiàn)proxy類對(duì)真實(shí)類的封裝對(duì)于粒度的控制有著重要的意義。但是靜態(tài)代理這個(gè)模式本身有個(gè)大問題,如果類方法數(shù)量越來越多的時(shí)候,代理類的代碼量是十分龐大的。所以引入動(dòng)態(tài)代理來解決此類問題。先看代碼:

package test;

public interface Subject   
{   
  public void doSomething();   
}
package test;

public class RealSubject implements Subject   
{   
  public void doSomething()   
  {   
    System.out.println( "call doSomething()" );   
  }   
}  
package test;

import java.lang.reflect.InvocationHandler;  
import java.lang.reflect.Method;  
import java.lang.reflect.Proxy;  

public class ProxyHandler implements InvocationHandler
{
    private Object tar;

    //綁定委托對(duì)象,并返回代理類
    public Object bind(Object tar)
    {
        this.tar = tar;
        //綁定該類實(shí)現(xiàn)的所有接口,取得代理類 
        return Proxy.newProxyInstance(tar.getClass().getClassLoader(),
                                      tar.getClass().getInterfaces(),
                                      this);
    }    

    public Object invoke(Object proxy , Method method , Object[] args)throws Throwable
    {
        Object result = null;
        //這里就可以進(jìn)行所謂的AOP編程了
        //在調(diào)用具體函數(shù)方法前,執(zhí)行功能處理
        result = method.invoke(tar,args);
        //在調(diào)用具體函數(shù)方法后,執(zhí)行功能處理
        return result;
    }
}
public class TestProxy
{
    public static void main(String args[])
    {
           ProxyHandler proxy = new ProxyHandler();
           //綁定該類實(shí)現(xiàn)的所有接口
           Subject sub = (Subject) proxy.bind(new RealSubject());
           sub.doSomething();
    }
}

看完代碼,現(xiàn)在我來回答,動(dòng)態(tài)代理的作用是什么:Proxy類的代碼量被固定下來,不會(huì)因?yàn)闃I(yè)務(wù)的逐漸龐大而龐大;可以實(shí)現(xiàn)AOP編程,實(shí)際上靜態(tài)代理也可以實(shí)現(xiàn),總的來說,AOP可以算作是代理模式的一個(gè)典型應(yīng)用;解耦,通過參數(shù)就可以判斷真實(shí)類,不需要事先實(shí)例化,更加靈活多變。

轉(zhuǎn)自知乎:https://www.zhihu.com/question/20794107

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容