I'working su un'applicazione db con ORmlite, il mio modello è simile a questo:È utile avere un DatabaseManager con tutte le funzioni di tutti gli oggetti del modello?
MDL oggetto ..
DatabaseTable(tableName = "UserCars")
public class CarMDL
{
@DatabaseField(generatedId = true)
private int _id;
@DatabaseField(columnName = "name")
private String _name;
//................. etc
}
// DB Helper class...
public class DatabaseHelper extends OrmLiteSqliteOpenHelper
{
private Dao<CarMDL,Integer> _carDao = null;
@Override
public void onCreate(SQLiteDatabase database,ConnectionSource connectionSource)
{
try
{
TableUtils.createTable(connectionSource, CarMDL.class);
} catch (SQLException e)
{
throw new RuntimeException(e);
} catch (java.sql.SQLException e)
{
e.printStackTrace();
}
}
public Dao<CarMDL, Integer> getCarDao()
{
if (null == _carDao)
{
try
{
_carDao = getDao(CarMDL.class);
}catch (java.sql.SQLException e)
{
e.printStackTrace();
}
}
return _carDao;
}
}
// DatabaseManager class...
public class DatabaseManager
{
static private DatabaseManager instance;
private DatabaseHelper helper;
static public void init(Context ctx)
{
if (null == instance)
{
instance = new DatabaseManager(ctx);
}
}
static public DatabaseManager getInstance()
{
return instance;
}
private DatabaseManager(Context ctx)
{
helper = new DatabaseHelper(ctx);
}
private DatabaseHelper getHelper()
{
return helper;
}
// All the Dao functions of all MDL objects are in this class, for example:
public List<CarMDL> getAllCars()
{
List<CarMDL> carLists = null;
try
{
carLists = getHelper().getCarDao().queryForAll();
} catch (SQLException e)
{
e.printStackTrace();
}
return carLists;
}
// This is another MDL object..
public List<MarkMDL> getAllMarks()
{
List<MarkMDL> marks = null;
try
{
marks = getHelper().getMarkDao().queryForAll();
} catch (SQLException e)
{
e.printStackTrace();
}
return marks;
}
}
Quindi la mia domanda è, è bene avere un DatabaseManager con tutte le funzioni di tutto oggetti del modello, come:
listCarById(int id)
listPlaneById(int id)
removeCar(int id)
removePlane(int id)
Etc .....
I in realtà non hanno un problema con le istanze DAO memorizzate nella cache locale. Osservandoli nel DaoManager è necessaria la creazione di un oggetto e non c'è penalità che io possa vedere. Questo è il modello usato da tutti gli oggetti di esempio. – Gray
ok, la combinazione di init e getInstance è molto bella! Ma non sono sicuro di mettere tutte le funzioni dei modelli in una singola classe, sarebbe meglio creare un altro DAO che estenda un'interfaccia con alcuni metodi comuni? ma non sono sicuro di come potrebbe essere ... Sono un po 'confuso – skabo
Vedere la mia risposta aggiornata. – wsanville