黑马程序员技术交流社区
标题:
java代理模式
[打印本页]
作者:
chenzhiyuan
时间:
2014-6-3 13:24
标题:
java代理模式
求一个ArrayList的代理?
作者:
雾里看花。
时间:
2014-6-3 13:56
public class Test2 {
// ArraiList代理类的测试
public static void main(String[] ages) {
MyArrayListInterface myArrayList =ArrayListProxy.getArrayListProxy();
myArrayList.add("AAAAA");
System.out.println(myArrayList.get(0));
}
// 定义一个ArrayList的代理类
static class ArrayListProxy {
// 定义一个返回ArrayListProxy对象的方法
public static MyArrayListInterface getArrayListProxy() {
MyArrayListInterface myArrayListProxy = (MyArrayListInterface) Proxy
.newProxyInstance(MyArrayListInterface.class
.getClassLoader(),
new Class[] { MyArrayListInterface.class },
new InvocationHandler() {
// 定义一个MyArrayList对象
private List myArrayList = new MyArrayList();
public Object invoke(Object proxy,
Method method, Object[] args)
throws Throwable {
// 定义记住此时时间的变量
long start = System.currentTimeMillis();
// 执行al的对应方法
Object objReturn = method.invoke(
myArrayList, args);
// 输出被调用方法执行的所需时间
System.out.println(method.getName()+"方法运行时间:"+(System
.currentTimeMillis()
- start)+"毫秒");
return objReturn;// 返回被调用方法执行结果
}
});
return myArrayListProxy;
}
}
}
// 定义一个实现MyArrayListInterface的类MyArrayList
class MyArrayList extends ArrayList implements MyArrayListInterface {
}
// 定义一个接口,同时继承ArrayList类实现的全部接口
interface MyArrayListInterface<E> extends Serializable, Cloneable, Iterable<E>,
Collection<E>, List<E>, RandomAccess {
}
作者:
博€$€海
时间:
2014-6-3 16:11
public static MyArrayListInterface getArrayListProxy() { MyArrayListInterface myArrayListProxy = (MyArrayListInterface) Proxy .newProxyInstance(MyArrayListInterface.class .getClassLoader(), new Class[] { MyArrayListInterface.class }
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2