我读过 Martin Fowler 的书籍中有关延迟加载的章节。
作者提供了我不知道的 C# 上通过 Ghost 对象延迟加载的示例。我试图理解整体含义,但没有成功,因为涉及很多类(class),而且本书没有包含足够的解释来理解。我还尝试使用 Google 搜索示例,但我发现的所有地方都将我链接到我也不知道的 PHP 示例。
您能提供有关 Java 的示例吗?
最佳答案
如果我正确理解你的要求(我正在查看 https://www.martinfowler.com/eaaCatalog/lazyLoad.html ),那么我不知道如何直接在 Java 中获得此功能;您必须使用其他原则之一并将其包装在幽灵对象包装器中。
基本上,您使用最小的值集初始化对象,然后仅在必要时计算其他字段值。类似下面的代码将为您提供一种从 Ghost
获取 Complicated
对象的惰性方法。我见过在从数据库加载信息时使用这样的对象,但不知道什么时候需要它,或者在计算特别复杂或重量级的哈希码时。
public class Ghost {
private final int count;
private boolean initialized = false;
private Complicated complicated = null;
public Ghost(int count) {
this.count = count;
}
public Complicated getComplicated(String extraValue) {
// could also check (here and below) this.complicated == null
// in that case doExpensiveOperation should not return null, and there shouldn't be other fields to initialize
if (!initialized) {
synchronized(this) { // if you want concurrent access
if (!initialized) {
complicated = doExpensiveOperation(extraValue);
initialized = true;
}
}
}
return complicated;
}
private Complicated doExpensiveLoad(String extraValue) {
// do expensive things with this.count and extraValue
// think database/network calls, or even hashcode calculations for big objects
}
}
关于java - java中如何使用Ghost对象实现延迟加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58243839/