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

标签 java android oop

我有一个代表数据库记录的抽象 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;
    }
}

最佳答案

您可以获得 Record 的类,前提是 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();
        ...
    }
    ...
}

关于java - 从抽象类创建对象实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16105753/

相关文章:

java - 如何将AdoptOpenJDK添加到Docker镜像中?

java - 计算txt文件中的周数

java - 如何使登录错误 ("Wrong username/password")在登录页面中更加具体

android - Android View Model 和 Singleton 类之间到底有什么区别

android - 使用自定义 ImageView 类,获取 NullPointerException

java - 使用 Java 计算标准差?

java - 在 Android OS 4.4.2/MobileFirst 混合应用程序上启用 TLS 1.2

php - PHP 构造函数的用途

java - 为什么一个类的绘制看不到另一类的数组?

c++ - 计算两点间距离时的编译错误