java - 从抽象类创建对象的实例

时间:2013-04-19 13:27:36

标签: java android oop

我有一个抽象的Record类,它表示数据库记录,它有两个抽象方法:getTable()和getColumns()。然后我有一个扩展Record的Customer类,我在这个类中实现了那些抽象方法。

我正在试图弄清楚如何获得所有客户的列表,但保持方法尽可能可重用,所以我更喜欢getAllRecords(记录记录)方法而不是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;
    }
}

4 个答案:

答案 0 :(得分:1)

如果Record的所有子类都具有no-arg构造函数,则可以获取Record的类。

Record newRecord = record.getClass().newInstance();

请注意,您只需传递类而不是对象本身。

你也可以通过一个负责实现正确班级的工厂。

interface RecordFactory {
    Record create();
}

class CustomerFactory implements RecordFactory {
    Record create() {
        return new Customer();
    }
}

public List<Record> getAllRecords(RecordFactory factory) {
    ...
    for(...) {
        ...
        Record record = factory.create();
        ...
    }
    ...
}

答案 1 :(得分:0)

一个奇怪的用例。我会将cursorToRecord方法抽象化。这将逻辑推入每个类,它知道如何从Cursor构建自己。

public abstract Record cursorToRecord(Cursor cursor, Record record);

答案 2 :(得分:0)

不直接回答您的问题,但请查看内容提供商的Android指南(https://developer.android.com/guide/topics/providers/content-providers.html)。它们允许灵活的数据访问以及其他好处。我发现它们值得初步学习和设置工作(特别是当使用w / Loaders时)

答案 3 :(得分:0)

反思怎么样?

Record newRecord = record.getClass().newInstance();