Java中的代理模式

代理模式:為其他對象提供一種代理以控制對這個對象的訪問软棺。在某些情況下乖酬,一個對象不適合或者不能直接引用另一個對象肠缔,而代理對象可以在客戶端和目標(biāo)對象之間起到中介的作用,通過代理對象完成真是對象的某些功能闷旧。

代理分為靜態(tài)代理和動態(tài)代理:

  • 靜態(tài)代理

  1. 首先創(chuàng)建一個業(yè)務(wù)接口(公司員工申請獎金的接口):
/**
 * 
 * 作者: luweicheng24
 * 時間: 2017年9月30日
 * 功能描述: 公司員工申請獎金的業(yè)務(wù)接口
 *
 */
public interface ApplyBonus {
    void result();// 申請結(jié)果
}

  1. 創(chuàng)建一個員工類,實(shí)現(xiàn)申請獎金的業(yè)務(wù)接口:
/**
 *  
 * 作者: luweicheng24
 * 時間: 2017年9月30日
 * 功能描述: 員工類
 *
 */
public class Employee implements ApplyBonus {
    public Employee(String position) {
        this.position = position;
    }
    private int salary; //獎金薪水
    private String position; // 職位
    public String getPosition() {
        return position;
    }
    public void setPosition(String position) {
        this.position = position;
    }
    public int getSalary() {
        return salary;
    }

    public void setSalary(int salary) {
        this.salary = salary;
    }
    @Override
    public void result() {
            System.out.println(position+"申請獎金的最后金額="+salary);
    }
    @Override
    public String toString() {
        return "Person [salary=" + salary + ", position=" + position + "]";
    }
    
}

  1. 創(chuàng)建一個員工的代理類實(shí)現(xiàn)根據(jù)員工職位決定獎金:
/**
* 
* 作者: luweicheng24
* 時間: 2017年9月30日
* 功能描述: 員工代理類
*
*/
public class EmployeeProxy implements ApplyBonus{
   private int salary; // 代理獎金
   private String position; // 代理對象的職位
   private ApplyBonus   employee; // 代理對象
   /**
    *  代理對象的構(gòu)造函數(shù)
    * @param employee 員工對象
    */
   public  EmployeeProxy(Employee employee) {
       this.employee = employee;
       this.position = employee.getPosition();
   }
   @Override
   public void result() {
       switch (position) {
       case "員工":
           salary = 1000;          
           break;
       case "主管":  
           salary  = 2000;
           break;
       }
   }
   @Override
   public String toString() {
       return "代理信息 [獎金 =" + salary + ", 職位=" + position + "]";
   }   
}

員工代理類通過傳入代理對象钧唐,對代理對象的信息進(jìn)行核實(shí)和確認(rèn)之后合理分發(fā)獎金忙灼,靜態(tài)代理通常在開發(fā)中為了補(bǔ)充被代理對象的邏輯,以及在前期開發(fā)中未做的一下工作任務(wù)钝侠。

動態(tài)代理

在Java中存在一個類 Proxy该园,該類是專門用來生成代理對象,然后執(zhí)行代理方法等功能帅韧,該類通過一個靜態(tài)方法生成代理里初,下面筆者貼部分源碼加上自己的注釋:

/**
*  loader : 需要代理對象的類加載器
*  interfaces 表示該代理對象實(shí)現(xiàn)的接口的集合
* InvocationHandler :一個包含invoke方法的接口
 * invoke方法是在代理對象每次調(diào)用被代理對象的方法的時候調(diào)用
*/
  public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)

InvocationHandler

該類的原文注釋:

/**
     * Processes a method invocation on a proxy instance and returns
     * the result.  This method will be invoked on an invocation handler
     * when a method is invoked on a proxy instance that it is
     * associated with.
     */
翻譯的意思:處理代理實(shí)例上的方法調(diào)用并返回 結(jié)果。 
這個方法將在調(diào)用處理程序中被調(diào)用當(dāng)一個方法在代理實(shí)例上被調(diào)用時關(guān)聯(lián)忽舟。

該類只包含一個方法:

public interface InvocationHandler {
/**
* proxy :表示代理對象
* method: 表示代理的方法
* args : 表示方法的參數(shù)
* 該方法在被代理對象中的任何方法執(zhí)行時執(zhí)行
*/
 public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;
}

所以需要在調(diào)用被代理對象方法執(zhí)行時添加邏輯双妨,就需要實(shí)現(xiàn)該類的接口,在invoke方法中叮阅,添加邏輯斥难。

了解InvocationHandler之后,繼續(xù)看ProxynewProxyInstance方法帘饶,在該方法中主要包含三個方法:

   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); // 1.通過類加載器和接口數(shù)組獲取代理類

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
           /**
           * constructorParams 表示InvocationHandler實(shí)現(xiàn)類的數(shù)組
          *    / ** parameter types of a proxy class constructor */
          *    private final static Class[] constructorParams =
          *    { InvocationHandler.class };
          */
            Constructor cons = cl.getConstructor(constructorParams); // 2. 獲取代理類的構(gòu)造方法
            return cons.newInstance(new Object[] { h }); // 3. 創(chuàng)建代理對象
        } 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());
        }
    }

對如上三個步驟解釋:

  1. Class<?> cl = getProxyClass(loader, interfaces); 獲取代理類,貼出源碼(省略了部分不重要的源碼),部分代碼添加注釋
public static Class<?> getProxyClass(ClassLoader loader,
                                         Class<?>... interfaces)
        throws IllegalArgumentException
    {
        if (interfaces.length > 65535) {  // 接口數(shù)組長度不能超過65535
            throw new IllegalArgumentException("interface limit exceeded");
        }

        Class<?> proxyClass = null; // 代理類的引用

        /* collect interface names to use as key for proxy class cache */
        String[] interfaceNames = new String[interfaces.length]; // 創(chuàng)建一個接口名組成的字符數(shù)組群扶,在之后的代理類的緩存鍵值對中作為Key及刻。

        // for detecting duplicates
        Set<Class<?>> interfaceSet = new HashSet<>(); // 創(chuàng)建一個set集合,存儲接口類
       // 便利接口數(shù)組竞阐,存儲接口類到set中
        for (int i = 0; i < interfaces.length; i++) {
            /*
             * Verify that the class loader resolves the name of this
             * interface to the same Class object.
             */
            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");
            }

            /*
             * Verify that the Class object actually represents an
             * interface.
             */
            if (!interfaceClass.isInterface()) {
                throw new IllegalArgumentException(
                    interfaceClass.getName() + " is not an interface");
            }

            /*
             * Verify that this interface is not a duplicate.
             */
            if (interfaceSet.contains(interfaceClass)) {
                throw new IllegalArgumentException(
                    "repeated interface: " + interfaceClass.getName());
            }
            interfaceSet.add(interfaceClass);

            interfaceNames[i] = interfaceName;
        }

        // 將接口名數(shù)組轉(zhuǎn)換成一個L
        List<String> key = Arrays.asList(interfaceNames);

        /*
         * Find or create the proxy class cache for the class loader.
         */
        // 從loaderToCache一個弱引用的Map key是一個類加載器 value 是如下的cache集合缴饭,
      // cache 是值為接口名字的list 值為 類加載器 如果緩存中沒有,添加到緩存
        Map<List<String>, Object> cache;
        synchronized (loaderToCache) {
            cache = loaderToCache.get(loader);
            if (cache == null) {
                cache = new 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) {
                    // proxy class already generated: return it
                    return proxyClass;
                } else if (value == pendingGenerationMarker) {
                    // proxy class being generated: wait for it
                    try {
                        cache.wait();
                    } catch (InterruptedException e) {
                    }
                    continue;
                } else {
                    cache.put(key, pendingGenerationMarker);
                    break;
                }
            } while (true);
        }
    // 查找代理的包名
        try {
            String proxyPkg = null;     // package to define proxy class in
            for (int i = 0; i < interfaces.length; i++) {
                int flags = interfaces[i].getModifiers();
                if (!Modifier.isPublic(flags)) {
                    String name = interfaces[i].getName();
                    int n = name.lastIndexOf('.');
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

            if (proxyPkg == null) {     // if no non-public proxy interfaces,
                proxyPkg = "";          // use the unnamed package
            }

            {
                /*
                 * Choose a name for the proxy class to generate.
                 */
                long num;
                synchronized (nextUniqueNumberLock) {
                    num = nextUniqueNumber++;
                }
                String proxyName = proxyPkg + proxyClassNamePrefix + num;
                /*
                 * Verify that the class loader hasn't already
                 * defined a class with the chosen name.
                 */

                /*
                 * Generate the specified proxy class.
                 */
                byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                    proxyName, interfaces);
                try {
                    proxyClass = defineClass0(loader, proxyName,
                        proxyClassFile, 0, proxyClassFile.length);
                } catch (ClassFormatError e) {
                    /*
                     * A ClassFormatError here means that (barring bugs in the
                     * proxy class generation code) there was some other
                     * invalid aspect of the arguments supplied to the proxy
                     * class creation (such as virtual machine limitations
                     * exceeded).
                     */
                    throw new IllegalArgumentException(e.toString());
                }
            }
            // add to set of all generated proxy classes, for isProxyClass
            proxyClasses.put(proxyClass, null);
     
        } finally {
            synchronized (cache) {  
                if (proxyClass != null) {
                    cache.put(key, new WeakReference<Class<?>>(proxyClass));
                } else {
                    cache.remove(key);
                }
                cache.notifyAll();// 喚醒等待的線程
            }
        }
        return proxyClass;
    }
  1. Constructor cons = cl.getConstructor(constructorParams);獲取代理類的構(gòu)造方法
  2. cons.newInstance(new Object[] { h });通過構(gòu)造方法創(chuàng)建一個實(shí)例骆莹。

好了颗搂,源碼分析完了,回到上面的問題幕垦,如何動態(tài)代理員工進(jìn)行獎金的分發(fā)丢氢,創(chuàng)建一個代理類實(shí)現(xiàn)InvocationHandler接口。

/*
 * 代理處理類
 */
public class DynamicProxy implements InvocationHandler{
    
    private Employee target;
    public DynamicProxy(Employee target) {
        this.target = target;
    }
        
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        /*
         * 代理類方法執(zhí)行時調(diào)用
         */
        if(method.getName().equals("result")){
            
        if(target.getPosition().equals("經(jīng)理")){
            target.setSalary(target.getSalary()+1000);
        }else {
            target.setSalary(target.getSalary()+500);
          }
        }
        
        Object obj = method.invoke(target, args);
        
        /*
         * 委托類方法執(zhí)行后操作
         */
        return obj;
    }
}

耗費(fèi)了好幾個小時了先改,下面來測試一下:


public class Proxytest {
    public static void main(String[] args) {
    ApplyBonus buyCar = (ApplyBonus)Proxy.newProxyInstance(Employee.class.getClassLoader(), new Class[]{ApplyBonus.class},new DynamicProxy(new Employee("經(jīng)理")));
    buyCar.result();    
    }

}

控制臺輸出結(jié)果:

經(jīng)理申請獎金的最后金額=1000

以上均是個人的理解疚察,如有疑問留言討論。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末仇奶,一起剝皮案震驚了整個濱河市貌嫡,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖岛抄,帶你破解...
    沈念sama閱讀 216,544評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件狈蚤,死亡現(xiàn)場離奇詭異赡鲜,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,430評論 3 392
  • 文/潘曉璐 我一進(jìn)店門盆犁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人氧秘,你說我怎么就攤上這事寻行。” “怎么了感凤?”我有些...
    開封第一講書人閱讀 162,764評論 0 353
  • 文/不壞的土叔 我叫張陵悯周,是天一觀的道長。 經(jīng)常有香客問我陪竿,道長禽翼,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,193評論 1 292
  • 正文 為了忘掉前任族跛,我火速辦了婚禮闰挡,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘礁哄。我一直安慰自己长酗,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,216評論 6 388
  • 文/花漫 我一把揭開白布桐绒。 她就那樣靜靜地躺著夺脾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪茉继。 梳的紋絲不亂的頭發(fā)上咧叭,一...
    開封第一講書人閱讀 51,182評論 1 299
  • 那天,我揣著相機(jī)與錄音烁竭,去河邊找鬼菲茬。 笑死,一個胖子當(dāng)著我的面吹牛派撕,可吹牛的內(nèi)容都是我干的婉弹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,063評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼腥刹,長吁一口氣:“原來是場噩夢啊……” “哼马胧!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起衔峰,我...
    開封第一講書人閱讀 38,917評論 0 274
  • 序言:老撾萬榮一對情侶失蹤佩脊,失蹤者是張志新(化名)和其女友劉穎蛙粘,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體威彰,經(jīng)...
    沈念sama閱讀 45,329評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡出牧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,543評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了歇盼。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片舔痕。...
    茶點(diǎn)故事閱讀 39,722評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖豹缀,靈堂內(nèi)的尸體忽然破棺而出伯复,到底是詐尸還是另有隱情,我是刑警寧澤邢笙,帶...
    沈念sama閱讀 35,425評論 5 343
  • 正文 年R本政府宣布啸如,位于F島的核電站,受9級特大地震影響氮惯,放射性物質(zhì)發(fā)生泄漏叮雳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,019評論 3 326
  • 文/蒙蒙 一妇汗、第九天 我趴在偏房一處隱蔽的房頂上張望帘不。 院中可真熱鬧,春花似錦杨箭、人聲如沸寞焙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,671評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽棺弊。三九已至,卻和暖如春擒悬,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背稻艰。 一陣腳步聲響...
    開封第一講書人閱讀 32,825評論 1 269
  • 我被黑心中介騙來泰國打工懂牧, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人尊勿。 一個月前我還...
    沈念sama閱讀 47,729評論 2 368
  • 正文 我出身青樓僧凤,卻偏偏與公主長得像,于是被迫代替她去往敵國和親元扔。 傳聞我的和親對象是個殘疾皇子躯保,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,614評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 本文動態(tài)代理部分內(nèi)容大量引自:http://www.ibm.com/developerworks/cn/java/...
    端木軒閱讀 411評論 0 0
  • 代理模式 在某些情況下,一個客戶不想或者不能直接引用一個對象澎语,此時可以通過一個稱之為“代理”的第三者來實(shí)現(xiàn)間接引用...
    籬開羅閱讀 451評論 0 5
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法途事,類相關(guān)的語法验懊,內(nèi)部類的語法,繼承相關(guān)的語法尸变,異常的語法义图,線程的語...
    子非魚_t_閱讀 31,623評論 18 399
  • 整體Retrofit內(nèi)容如下: 1、Retrofit解析1之前哨站——理解RESTful 2召烂、Retrofit解析...
    隔壁老李頭閱讀 3,236評論 2 10
  • 漂亮的花 漂亮冰花 超級小可愛 綠色的浦公英 紅花朵朵 紅粉綠相配 大大寬寬的大橋 藍(lán)藍(lán)的大牛 超級肥的肥豬肉
    0我就是我1閱讀 223評論 0 1