【发布时间】:2015-11-08 15:55:50
【问题描述】:
好的,这是一个更理论的问题。
我有PlayerRepository。这是一个用于对我的 SQLite 数据库进行操作的类。我已经在那里实现了select、insert、update 等操作。
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();
}
}
}
如您所见,当我创建存储库时,如果数据库之前未打开,我将打开它。为此,我需要传递应用程序/活动的Context。这不是问题。
但有时我想在活动之外使用我的存储库。在某种需要获取数据的工具类中。所以我有两种方法可以考虑
我在活动中获取数据并将其传递给我的工具类/方法,因此我不需要在其中使用存储库。这不是很灵活
我需要将上下文传递给我的工具类/方法。但这意味着每种操作都需要接收上下文,我不确定这是不是一个好方法
我错过了什么吗?有没有更好的处理方法?
【问题讨论】:
标签: java android sqlite architecture software-design