【问题标题】:Design Pattern: Using Null to minimize heavy Database Queries设计模式:使用 Null 来减少繁重的数据库查询
【发布时间】:2016-07-27 21:50:21
【问题描述】:

我目前是一名初级开发人员,正在从事一些副项目,试图进入 android java 开发的世界。

然而,我今天的问题适用于大多数 OOP 驱动的概念。

让我进入正题。我的 Android 应用程序有一些活动和方法最终会产生非常繁重的数据库查询,这使得它变得非常慢,尤其是因为我使用 ORM (SugarORM) 来使事情变得更快(开发方面)并减少错误。

我已经找到了一个解决方案,它似乎工作得很好,但是,我认为最好在将它集成到应用程序之前询问它。只是想知道这通常是否是一种不好的做法。

不幸的是,谷歌并不是很有帮助,主要是因为搜索类似问题所需的关键字总是会将我带到空对象模式:|

我的实现示例:

private List<Book> mBooks;

public List<Book> getBooks() {
    if (this.mBooks == null)
        this.mBooks = SugarRecord.listAll(Book.class);
    return this.mBooks;
}

public List<Book> onBookListUpdated() {
    this.mBooks = null;
}

如您所见,这可确保查询只执行一次(至少在预期列表发生变化之前)。

我需要知道的是,如果这有意义,有多少程序员会真正做这样的事情,如果它是一件事,它叫什么?

此外,如果“可以”这样做,将这个逻辑包装在一个类中会是一个好主意吗?

这样说:

public class FastList<T> {

    public interface iFastList<TT> {
        List<TT> reloadList();
    }

    public FastList(iFastList<T> inCallback) {
        this.callback = inCallback; 
    }

    private iFastList<T> callback

    private List<T> currentList;

    public List<T> getList() {
        if (this.currentList == null)
            this.currentList = this.callback.reloadList();
        return this.currentList;
    }

    public void onListChanged() {
        this.currentList = null;
    }
}

提前感谢所有需要时间来回答的人。

【问题讨论】:

  • 很常见。它有几个缺点。首先,如果您更改列表中的任何内容,您必须确保调用更新。它很容易忘记。其次,您可以在任何时候使用这样的全局变量时遇到线程问题。但好处往往是值得付出代价的。
  • 非常感谢您的回答,现在我知道它叫什么,我可以自己阅读它。谢谢

标签: android database oop design-patterns null


【解决方案1】:

Lazy Intitailization 它在objective-c中很受欢迎

- (NSMutableArray *) myArray {
    if(!_myArray) {
        _myArray = [[NSMutableArray alloc] init];
    }
    return _myArray;
}

【讨论】:

  • 它在各种语言中都非常流行。整个语言都是围绕惰性计算构建的,请参阅 Haskell 和其他函数式语言。
猜你喜欢
  • 2020-06-02
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 1970-01-01
相关资源
最近更新 更多