cuiyi's blog(崔毅 crazycy)

          記錄點滴 鑒往事之得失 以資于發展
          數據加載中……

          我對設計模式的理解:Dynamic Proxy模式

          代理模式(Proxy,這里側重于Dynamic Proxy)可以理解成給一個對象提供一個代理對象,這個代理對象就是把原對象進行包裝,使其與調用處理器相關聯。
          ??? 因為代理對象和真實對象具有相同的接口,客戶訪問時,通過接口調用代理實例的方法,這個調用會被分發到該實例對應的處理器。處理器在把客戶端調用傳遞給真實的對象之前或者之后,可執行某個操作,也可以選擇不把這個調用傳遞給真實的對象。
          ???
          ???產生代理對象的過程就是將原對象和調用處理器邦定的過程,如下:
          Proxy.newProxyInstance(真實對象實例.getClass().getClassLoader(), 真實對象實例.getClass().getInterfaces(),?與真實對象關聯的調用處理器實例);

          ?? 示例:
          public interface AnInterface {
          ?void say();
          }


          public class AClass implements AnInterface {
          ?public AClass() {
          ??System.out.println("AClass:AClass()");
          ?}
          ?public void say() {
          ??System.out.println("AClass:say()");
          ?}
          }


          public class MyHandler implements InvocationHandler {
          ?private Object realObj;
          ?private MyHandler() {
          ??}
          ?public Object bind(Object realObj) {
          ????this.realObj = realObj;
          ??? return Proxy.newProxyInstance(realObj.getClass().getClassLoader(),
          ????realObj.getClass().getInterfaces(),?this);
          ?}
          ?public Object invoke(Object proxy, Method md, Object[] args) throws Throwable {
          ??Object obj = null;
          ??System.out.println("invoke()");
          ??obj = md.invoke(realObj, args);
          ??return obj;
          ?}
          }

          public class Test {
          ?public static void main(String[] args) {
          ? MyHandler??handler = new MyHandler?();
          ? AnInterface?proxyObj = handler.bind(new AClass());
          ??proxyObj.say();
          ?}
          }

          posted on 2006-04-29 14:12 crazycy 閱讀(1023) 評論(0)  編輯  收藏 所屬分類: Design Pattern、JEE Pattern

          主站蜘蛛池模板: 九台市| 高淳县| 通化市| 云阳县| 洛浦县| 弥渡县| 葫芦岛市| 九龙坡区| 台安县| 霸州市| 庄河市| 庆云县| 肥城市| 南安市| 克山县| 广灵县| 靖宇县| 太谷县| 津南区| 西青区| 自治县| 庆城县| 会理县| 丹阳市| 太白县| 巴东县| 海淀区| 德格县| 屯留县| 兴文县| 白沙| 孟州市| 和龙市| 石门县| 成安县| 上杭县| 合山市| 沙坪坝区| 永仁县| 沛县| 南靖县|