首页 > 学院 > 开发设计 > 正文

设计模式研究--Proxy Model

2019-11-18 11:26:01
字体:
来源:转载
供稿:网友

这是一个动态代理的例子,今天时间比较晚了,抽时间我会做一下分析.

package javapatterns;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.PRoxy;
import java.util.List;
import java.util.Vector;
/**
 *  Proxy Model 的研究
 * <p>Title:VectorProxy.java</p>
 * <p>Description:</p>
 * <p>Copyright:Copyright (c) 2004 DSII,Inc</p>
 * <p>Company:DSII,Inc</p>
 * @author Morgan 2004-11-8
 * @version 1.0
 */
public class VectorProxy implements InvocationHandler {
 private Object proxyobj;

 public VectorProxy(Object obj) {
  proxyobj = obj;
 }

 public static Object factory(Object obj) {
  Class cls = obj.getClass();

  return Proxy.newProxyInstance(
   cls.getClassLoader(),
   cls.getInterfaces(),
   new VectorProxy(obj));
 }

 public Object invoke(Object proxy, Method method, Object[] args)
  throws Throwable {
  System.out.println("before calling " + method);

  if (args != null) {
   for (int i = 0; i < args.length; i++) {
    System.out.println(args[i] + "");
   }
  }
  Object o = method.invoke(proxyobj, args);

  System.out.println("after calling " + method);
  return o;
 }

 public static void main(String[] args) {
  List v = null;
  v = (List) factory(new Vector(10));
  v.add("New");
  v.add("York");
 }
}



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表