我只知道用于 AOP 的动态代理。
但是,它似乎也可以用于延迟加载。
以下来自文章的示例旨在证明这一点。
但是,我不明白这与普通访问器有何不同,以及这里“懒惰”加载的究竟是什么?
任何有助于理解作者通过延迟加载的意图的帮助表示赞赏。
private Category tupleToObject(Serializable[] tuple) {
Category category = new Category((String)tuple[1],
(YearMonthDay) tuple[2]);
category.setId((Long) tuple[0]);
category.setParent(lazyGet((Long) tuple[3]));
return category;
}
protected CategoryItf lazyGet(Long id) {
if (id == null) {
return null;
}
return (CategoryItf)Proxy.newProxyInstance(
CategoryItf.class.getClassLoader(),
new Class[] { CategoryItf.class },
new LazyLoadedObject() {
protected Object loadObject() {
return get(id);
}
});
}
public abstract class LazyLoadedObject implements InvocationHandler {
private Object target;
public Object invoke(Object proxy,
Method method, Object[] args)
throws Throwable {
if (target == null) {
target = loadObject();
}
return method.invoke(target, args);
}
protected abstract Object loadObject();
}
这与以下内容有何不同:
private Category tupleToObject(Serializable[] tuple) {
Category category = new Category((String)tuple[1],
(YearMonthDay) tuple[2]);
category.setId((Long) tuple[0]);
category.setParent(get((Long) tuple[3]));
return category;
}
在这两种情况下,仅在需要时才创建父级。