java - java中如何使用Ghost对象实现延迟加载?

标签 java architecture lazy-loading

我读过 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/

相关文章:

java - 尝试单击弹出窗口的按钮时出现 NoSuchElementException

java - Windows 2008 服务上的 java 服务的 Tmp 问题

iOS:对于一个简单的 iOS 应用程序来说,这是一个合理的设计模式吗?

c# - 使用 Fluent NHibernate 加载完整对象

angular - 如何将子组件设置为路由器导出的默认路由?

javascript - 加载页面上的所有图像并等待完成

java - 将日历时间从java转换为EDM

java - 返回对存储在对象字段之一中的可变对象值的引用会暴露对象的内部表示

c# - 在 DDD 架构中,我应该在哪里放置与按角色用户过滤数据相关的查询逻辑

.net - 存储库或数据访问方法中的方法上的 'Find' 和 'Get' 动词有什么区别?