我的类从SQLiteOpenHelper派生越来越巨大我的、巨大、SQLiteOpenHelper

2023-09-06 02:09:34 作者:软耳兔兔

我的类从 SQLiteOpenHelper 来源是越来越大了的时候。在发言时间是1500多行的是不被认为是很酷的code。可能有一些优雅的解决方案,从不断增长的prevent它,即通过撕成小块分离。不知道那些撕成小块是虽然。有人说,这是一个不好的做法,自提类继承,因为它会导致不当行为数据库创建/升级程序。任何提示?非常感谢!

My class derived from SQLiteOpenHelper is getting bigger and bigger over a time. At the speaking time it is more than 1500 lines of code which is not considered to be cool. There might be some elegant solution to prevent it from growing, i.e. separating by peaces. Not sure what those peaces to be though. Some people say it is a bad practice to inherit from the mentioned class because it leads misbehavior to database creation/upgrade procedures. Any hint? Thanks a lot!

推荐答案

是的,在开发中所示的例子。网站做鼓励创造一个怪物级的,你很难$ C C每个表和列的名称$。这是一个烂摊子。您可能要创建一个类来处理每个表。这些类可以作为数据访问对象为每个表。

Yes, the examples shown in the dev. site do encourage the creation of a monster class where you hardcode the names of every table and column. This is a mess. You might want to create a class to handle each table. These classes can act as Data Access Objects for each table.

这是我使用的:

    public interface DataAccessObject<E> {

        public void onCreate(SQLiteDatabase db);

        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);

        public void create(E... params);

        public E[] retrieve(E... params);

        public void update(E... params);

        public void delete(E... params);

    }

然后我code为每个表的实现。通用tipe E为通常的POJO。请注意,我不是在与混合类拟牵住数据(POJO)中的类分管坚持-检索数据(DAO的)。例如,一个POJO可能是,其变量(颜色,年份等)。然后我会codeA CarDAO延长 DataAccessObject&LT;车&GT; 。这DAO类是负责POJO的变量映射到数据库列,查询表,并以书面方式吧。

Then I code an implementation for each table. The generic tipe E are usually pojos. Notice I'm not mixing the classes intended to just hold data (pojos) with the classes in charge of persisting-retrieving data (DAO's). For instance a pojo could be Car, with its variables (color, year, etc). Then i'd code a CarDAO extending DataAccessObject<Car>. And this DAO class is in charge of mapping the pojo's variables to DB columns, querying the table and writting to it.

最后,你可以有一个是注射了DAO的一个SQLiteOpenHelper,和代表的东西对每个表给他们。这些DAO实现的是那些有表和列名,常量。它们可以根据需要对一些复杂的查询互相交谈。 (请注意,这也是这种方法的缺点之一:当您需要涉及许多表和列的查询产生一个利落的设计并不简单)。

Finally, you can have a SQLiteOpenHelper that is injected with the DAOs, and delegates stuff for each table to them. These DAO implementations are the ones having table and column name constants. And they can talk to each other if needed for some complex queries. (Notice how this is also one of the drawbacks of this approach: producing a neat design is not straightforward when you need queries involving many tables and columns).