行為模式--代理Proxy模式(Java)

來源:互聯網
上載者:User

標籤:ant   之間   ...   java   file   介面   res   put   ping   

代理(AOP切面的雛形):

題記:顧名思義就是將某件事,某個東西的使用權進行為讓授權轉移。代理相當於中介(不同於中介者模式),在原本操作的類之間添加了一個橋樑。但代理不能去修改原有目標。比如:一個人要買       房,讓中介幫忙給看個房,但中介不能將原有看房這件事變更為看車。他可以對看房提出各種要求和諮詢。

回到程式的角度,調用者將調用某些共性類的處理交由代理類處理,代理類根據調用者的要求即滿足什麼情況可以調用,什麼情況不能調用,(賣房者委託中介100萬以上賣,100萬以下不賣)對處理做前後的封裝,但是代理類不能去改變被調用類的內部處理(可口可樂中國區可修改可口可樂封裝,但不能在沒授權情況下去更改可口可樂飲料)。

1.靜態代理

2.動態代理

1.靜態代理:對指定介面類做代理,通過對執行方法前後做處理,來實現代理的作用。因對指定介面類,因此可做某些特定類的特殊處理。

 1 /** 2  * 靜態代理,也被稱為decate模式 3  *  4  * @author DennyZhao 5  * @date 2017年6月13日 6  * @version 1.0 7  */ 8 public class AnimalProxyFactory implements AnimalFactory { 9     /**10      * 序號11      */12     private static final long serialVersionUID = -3421761900236678842L;13     14     15     private AnimalFactory animal;16     17     public AnimalProxyFactory(AnimalFactory animal){18         this.animal = animal;19     }20     @Override21     public int getLegs() {22         System.out.println("before....action");23         int legs = animal.getLegs();24         System.out.println("after....action");25         return legs;26     }27 28 }
View Code

測試Main:

  // 靜態代理
  Rabit rabit = new Rabit();
  AnimalProxyFactory proxyFactory = new AnimalProxyFactory(rabit);
  System.out.println(proxyFactory.getLegs());    

運行結果: 

  >>>before....action
  >>>after....action
  >>>4  

       2.動態代理:動態代理通過Proxy類建立代理,通過InvokationHandler去調用方法。

 1 package pattern.creation.factory; 2  3 import java.io.FileInputStream; 4 import java.io.FileNotFoundException; 5 import java.io.IOException; 6 import java.lang.reflect.Proxy; 7 import java.util.Properties; 8  9 /**10  * 動態代理模式11  * 12  * @author DennyZhao13  * @date 2017年6月13日14  * @version 1.015  */16 public class ProxyFactory {17     private static final String CLASS_NAME_PATH = "pattern/classname.properties";18     @SuppressWarnings("unchecked")19     public static <T> T getInstance(String name) throws IllegalArgumentException, InstantiationException, IllegalAccessException{20         String className = getClassName(name);21         T result = null;22         try {23             Class clazz = Class.forName(className);24             result = (T)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), new MyInvocationHandler(clazz.newInstance()));25         } catch (ClassNotFoundException e) {26             e.printStackTrace();27         }28         return result;29     }30 31     /**32      * 擷取類名稱33      * @return34      */35     private static String getClassName(String name) {36         Properties pro = new Properties();37         try {38             String url = ProxyFactory.class.getClassLoader().getResource("").getPath() + CLASS_NAME_PATH;39             pro.load(new FileInputStream(url));40         } catch (FileNotFoundException e) {41             e.printStackTrace();42         } catch (IOException e) {43             e.printStackTrace();44         }45         return (String)pro.get(name);46     }47 }
View Code

     注意* : 代理面向的是介面,因此委託的類都需要實現指定的介面。

      result = (T)Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), new MyInvocationHandler(clazz.newInstance()));

       clazz.getInterfaces():如果一個clazz實現多個介面,此處要傳入介面Class。

      MyInvocationHandler 實現 InvocationHandler介面,裡面要實現一個invoke方法,在這個invoke方法中填寫處理。

MyInvocationHandler 

// 可通過放射機制,來處理特殊類的特殊請求。

測試Main:

// 動態代理,AOP切面的雛形做法
AnimalFactory sheep = ProxyFactory.getInstance("sheep");
sheep.getLegs();

// 動態代理,AOP切面的做法
PlantFactory plum = ProxyFactory.getInstance("plum");
plum.getColor();

// 動態代理,AOP切面的做法
AnimalFactory rabit0 = ProxyFactory.getInstance("rabit");
rabit0.getLegs();

結果:

before-------
sheep has 4 legs....
after-------
before-------
plum green purple....
after-------
before-------
兔子是特殊的
after-------

 

行為模式--代理Proxy模式(Java)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.