如何在Java中使用Ghost对象实现延迟加载?

时间:2019-10-04 22:36:29

标签: java architecture lazy-loading

我已经读过马丁·福勒(Martin Fowler)关于延迟加载的书。

作者提供了一个我不知道的通过C#上的Ghost对象进行延迟加载的示例。我试图理解整体含义,但是我没有成功,因为其中涉及很多课程,并且本书没有足够的理解力。我也尝试使用Google搜索示例,但是我发现的所有地方都将我链接到了我也不知道的PHP示例。

您能否提供有关Java的示例?

1 个答案:

答案 0 :(得分:1)

如果我正确理解了您的要求(正在查看https://www.martinfowler.com/eaaCatalog/lazyLoad.html),那么我就不知道一种直接在Java中获得此功能的方法。您将不得不使用其他原则之一,并将其​​包装在鬼对象包装器中。

基本上,您使用最小的一组值初始化对象,然后仅在必要时才计算其他字段值。类似于下面的代码,您可以通过一种懒惰的方式从Complicated中获得Ghost对象。我见过从数据库加载信息时使用过这样的对象,但不知道何时需要它,或者不知道何时计算特别复杂或重量级的哈希码。

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
    }
}
相关问题