gpt4 book ai didi

java - 如何在使用数据库存储库的方法之间正确传递上下文?

转载 作者:行者123 更新时间:2023-11-30 08:48:20 25 4
gpt4 key购买 nike

好吧,这是一个更具理论性的问题。

我有 PlayerRepository。这是一个用于对我的 SQLite 数据库执行操作的类。我在那里实现了 selectinsertupdate 等操作。

public PlayerRepository(Context context) {
super(context, com.fixus.portals.model.Player.class);
open();
}
构造函数中的

super 是因为 PlayerRepository extends Repository 这也是我的类。 Repository 最重要的部分就是这个

public class Repository<T> {
protected static SQLiteDatabase db = null;
protected static MainHelper helper = null;
protected Context context;
private Class<T> type;

public Repository(Context context, Class<T> classz) {
this.type = classz;
this.context = context;
if(helper == null) {
helper = new MainHelper(context.getApplicationContext());
}
}

public static void open() {
if(db == null) {
db = helper.getWritableDatabase();
}
}
}

如您所见,当我创建存储库时,如果数据库之前未打开,我将打开它。为此,我需要传递应用程序/Activity 的 Context。那不是问题

但有时我想在 Activity 之外使用我的存储库。在某种需要获取数据的工具类中。所以我有两种方法可以考虑

  1. 我在 Activity 中获取数据并将其传递到我的工具类/方法,因此我不需要在其中使用存储库。这不是很灵活

  2. 我需要将上下文传递给我的工具类/方法。但这意味着每一种操作都需要接收上下文,我不确定这是一个好方法

我错过了什么吗?有没有更好的方法来处理它?<​​/p>

最佳答案

您总是需要一个上下文来访问 SQLite 数据库,因此您可以做的是更改该特定工具类的构造函数并将 PlayerRepository 的新实例作为参数传递。这可以防止您的工具类本身需要上下文。

Imo 如果你有多个使用数据库的类,最好的方法是创建一个新类,它的唯一工作是执行数据库操作,并将所有需要的操作放在该类中。

只需使用 ToolsPlayerRepository 构造函数的当前 Activity 的上下文创建此数据库类的对象。这样,您的 PlayerRepositoryTools 类都不需要 Context,并且两者都可以对数据库进行操作。即使您真的需要 PlayerRepository 中的 Context,最好始终将所有与数据库相关的功能集中在一个类中。

关于java - 如何在使用数据库存储库的方法之间正确传递上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32026224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com