I'working與ORmlite一個數據庫應用程序,我的模式是這樣的:是否有一個DatabaseManager包含所有模型對象的所有功能?
MDL對象..
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;
}
}
所以我的問題是,它的好處是有一個的DatabaseManager與所有所有功能模型對象,如:
listCarById(int id)
listPlaneById(int id)
removeCar(int id)
removePlane(int id)
等.....
我實際上對本地緩存的DAO實例沒有問題。在DaoManager中查找它們需要創建一個對象,並且我不能看到任何懲罰。這是所有示例對象使用的模式。 – Gray 2012-04-09 23:07:07
好吧,結合初始化和getInstance看起來不錯!但我不知道把所有的模型功能在一個類中,會更好地創建一個擴展一些常見方法的接口另一個DAO的?但我不確定這怎麼會是......我有點困惑 – skabo 2012-04-10 13:17:32
看到我更新的答案。 – wsanville 2012-04-10 13:39:54