我有一个表示数据库记录的抽象 Record 类,它有两个抽象方法:getTable() 和 getColumns()。然后我有一个扩展 Record 的 Customer 类,我在这个类中实现了这些抽象方法。
我试图弄清楚如何获取所有客户的列表,但要尽可能地保持方法可重用,所以我更喜欢 getAllRecords(Record record) 方法而不是 getAllCustomers() 方法。
这是我到目前为止所拥有的。我无法创建新的 Record() 对象,因为它是抽象的,需要创建传入的类的实例。
//i'd like to do something like this to get all of the Customers in the db
// datasource.getAllRecords(new Customer());
public List<Record> getAllRecords(Record record) {
List<Record> records = new ArrayList<Record>();
Cursor cursor = database.query(record.getTable(),
record.getColumns(), null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Record record = cursorToRecord(cursor, record);
records.add(record);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return records;
}
private Record cursorToRecord(Cursor cursor, Record record) {
Record record = new Record(); <-- somehow clone a new instance of the record that was passed in
record.setId(cursor.getLong(0));
record.setValue("aKey",cursor.getString(1));
return record;
}
使用某种 RecordRegistry 对象而不是为每个 Record 子类设置单独的工厂类是否有意义?
class RecordRegistry{
private static final List<Record> RECORDS;
static {
final List<Record> records = new ArrayList<Record>();
records.add(new Customer());
records.add(new Company());
RECORDS = Collections.unmodifiableList(records);
}
public List<Record> allRecords(){
return RECORDS;
}
public Record buildRecord(Class cClass){
String className = cClass.getName().toString();
if(className.equalsIgnoreCase("customer")){
return new Customer();
}else if(className.equalsIgnoreCase("company")){
return new Company();
}
return null;
}
}