简体   繁体   English

使用 Java 中的静态工厂方法和常量进行生成

[英]Generifying with static factory methods and constants in Java

In my Android app, I have some very similar classes, let's call them FooA and FooB .在我的 Android 应用程序中,我有一些非常相似的类,我们称它们为FooAFooB

For each of these classes, I have a schema class that contains constants for the columns of the table - FooASchema and FooBSchema :对于这些类中的每一个,我都有一个架构类,其中包含表列的常量 - FooASchemaFooBSchema

public final class FooASchema {

    public static final String TABLE_NAME = "foo_a_table";
    public static final String COL_CATEGORY_ID = "category_id";
    public static final String COL_PROPERTY_A = "property_a";
    public static final String COL_PROPERTY_B = "property_b";
    // COL_PROPERTY_C = ...

}


public final class FooBSchema {

    public static final String TABLE_NAME = "foo_b_table";
    public static final String COL_CATEGORY_ID = "category_id";
    public static final String COL_OTHER_PROPERTY_A = "other_property_a";
    // COL_OTHER_PROPERTY_B = ...

}

Both FooA and FooB have a static factory method that enables me to create them using a Cursor : FooAFooB都有一个静态工厂方法,使我能够使用Cursor创建它们:

public static FooA from(Cursor cursor) {
    int categoryId = cursor.getInt(cursor.getColumnIndex(FooASchema.COL_CATEGORY_ID));
    String propertyA = cursor.getString(cursor.getColumnIndex(FooASchema.COL_PROPERTY_A));
    String propertyB = cursor.getString(cursor.getColumnIndex(FooASchema.COL_PROPERTY_B));
    // int propertyC = ...

    return FooA(id, propertyA, propertyB, ...);
}


public static FooB from(Cursor cursor) {
    int categoryId = cursor.getInt(cursor.getColumnIndex(FooBSchema.COL_CATEGORY_ID));
    int otherA = cursor.getInt(cursor.getColumnIndex(FooASchema.COL_OTHER_PROPERTY_A));
    // String otherB = ...

    return FooB(id, otherA, otherB, ...);
}

Finally, I have two util classes that I use to retrieve data from the tables:最后,我有两个 util 类可用于从表中检索数据:

public final class FooAUtils {

    public static ArrayList<FooA> getFooAs(Context context, int categoryId) {
        ArrayList<FooA> fooAs = new ArrayList<>();

        Cursor cursor = MyDbHelper.getInstance(context).getReadableDatabase.query(
                FooASchema.TABLE_NAME,
                null,
                FooASchema.COL_CATEGORY_ID + "=?",
                new String[] {String.valueOf(categoryId)},
                null,
                null,
                null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            fooAs.add(FooA.from(cursor));
            cursor.moveToNext();
        }
        cursor.close();
        return fooAs;
    }

    // ...
}


public final class FooBUtils {

    public static ArrayList<FooA> getFooBs(Context context, int categoryId) {
        ArrayList<FooB> fooBs = new ArrayList<>();

        Cursor cursor = MyDbHelper.getInstance(context).getReadableDatabase.query(
                FooBSchema.TABLE_NAME,
                null,
                FooBSchema.COL_CATEGORY_ID + "=?",
                new String[] {String.valueOf(categoryId)},
                null,
                null,
                null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            fooBs.add(FooB.from(cursor));
            cursor.moveToNext();
        }
        cursor.close();
        return fooBs;
    }

    // ...
}

You can see that most of the code between FooA -related classes and FooB -related classes are very similar, and especially in the util classes - where the code is almost identical.您可以看到FooA相关类和FooB相关类之间的大多数代码非常相似,尤其是在 util 类中 - 代码几乎相同。

I want to try to reduce this duplication, and I have been trying to do so using generics (I've read about them, but I haven't yet used them in a project).我想尝试减少这种重复,并且我一直在尝试使用泛型(我已经阅读过它们,但我还没有在项目中使用它们)。

For example, I want to be able to have a generic util class.例如,我希望能够拥有一个通用的 util 类。 Here's how I thought I could implement it:这是我认为我可以实现它的方式:

public final class FooUtils {

    public static <T> get(Context context, int categoryId) {
        ArrayList<T> items = new ArrayList<>();

        Cursor cursor = MyDbHelper.getInstance(context).getReadableDatabase.query(
                BaseSchema.TABLE_NAME,
                null,
                BaseSchema.COL_CATEGORY_ID + "=?",
                new String[] {String.valueOf(categoryId)},
                null,
                null,
                null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            items.add(T.from(cursor)); // ??
            cursor.moveToNext();
        }
        cursor.close();
    }

    // ...

}

Where:在哪里:

public interface BaseSchema {

    public static final String TABLE_NAME; // can't make this abstract?

    public static final String COL_CATEGORY_ID = "category_id";

}

public final class FooASchema implements BaseSchema { ... }


public final class FooBSchema implements BaseSchema { ... }

But as you can see, I can't do T.from(cursor) , and I can't have an abstract constant TABLE_NAME that the subclasses can implement.但是正如你所看到的,我不能做T.from(cursor) ,我不能有一个子类可以实现的抽象常量TABLE_NAME

How can I call my static factory method in this way?如何以这种方式调用我的静态工厂方法?

Is there a better way of approaching this and reducing code duplication?有没有更好的方法来解决这个问题并减少代码重复?

In your actual code you don't use an instance of the class to invoke the form() factory, you use a static method of the class :在您的实际代码中,您不使用类的实例来调用form()工厂,而是使用类的静态方法:

fooAs.add(FooA.from(cursor));

With generics, you cannot use the parameterized type to invoke a method on it like that items.add(T.from(cursor));使用泛型,你不能使用参数化类型来调用它的方法,比如items.add(T.from(cursor)); since the generic was erased after the compilation.因为泛型在编译后被删除了。

In your case, I see two ways of handling the problem :在您的情况下,我看到两种处理问题的方法:

  • introducing a abstract base class with the common method and an abstract method that subclasses have to implement to create a Foo instance ( FooA , FooB ).引入具有公共方法的抽象基类和子类必须实现以创建Foo实例( FooAFooB )的抽象方法。

  • keeping your way of doing and introducing an interface to create a Foo instance.保持你的方式并引入一个接口来创建一个Foo实例。 You would have two implementation of it.你会有两个实现它。 One for FooA and another one for FooB and you could provide a instance of it in the FooUtils.get() method.一个用于FooA ,另一个用于FooB ,您可以在FooUtils.get()方法中提供它的一个实例。

With the first option you could do the following.使用第一个选项,您可以执行以下操作。

Base class基类

public abstract class AbstractFooProcessing<T extends Foo> {

    public abstract T createFooInstance(Cursor cursor);

    public ArrayList<T> get(Context context, int categoryId) {
        ArrayList<T> items = new ArrayList<>();

        Cursor cursor = MyDbHelper.getInstance(context).getReadableDatabase.query(
                BaseSchema.TABLE_NAME,
                null,
                BaseSchema.COL_CATEGORY_ID + "=?",
                new String[] {String.valueOf(categoryId)},
                null,
                null,
                null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            items.add(createFooInstance(cursor));
            cursor.moveToNext();
        }
        cursor.close();
    }

    // ...

}

FooAProcessing FooA处理

public class FooAProcessing extends AbstractFooProcessing<FooA>{

    @Override
    public FooA createFooInstance(Cursor cursor) {
        return FooA.from(cursor);
    }

}

FooBProcessing FooB处理

public class FooBProcessing extends AbstractFooProcessing<FooB>{

    @Override
    public FooB createFooInstance(Cursor cursor) {
        return FooB.from(cursor);
    }

}

With the second option you could do the following.使用第二个选项,您可以执行以下操作。

FooProcessing interface FooProcessing 接口

public interface FooProcessing<T extends Foo> {    
    T createFooInstance(Cursor cursor);            
}

FooProcessingA FooProcessingA

public class FooAProcessing implements FooProcessing<FooA>{

    @Override
    public FooA createFooInstance(Cursor cursor) {
        return FooA.from(cursor);
    }   
}

FooProcessingB FooProcessingB

public class FooBProcessing implements FooProcessing<FooB>{

    @Override
    public FooB createFooInstance(Cursor cursor) {
        return FooB.from(cursor);
    }
}

FooUtils updated so that get() takes as argument a FooProcessing factory instance. FooUtils已更新,以便get()FooProcessing工厂实例作为参数。

public final class FooUtils {

    public static <T extends Foo> ArrayList<T> get(Context context, int categoryId, FooProcessing<T> fooProcessing) {
        ArrayList<T> items = new ArrayList<>();

        Cursor cursor = MyDbHelper.getInstance(context).getReadableDatabase.query(
                BaseSchema.TABLE_NAME,
                null,
                BaseSchema.COL_CATEGORY_ID + "=?",
                new String[] {String.valueOf(categoryId)},
                null,
                null,
                null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            items.add(fooProcessing.createFooInstance(cursor)); // ??
            cursor.moveToNext();
        }
        cursor.close();
    }
    // ...
    return items;

}

You can now call the FooUtils.get() method in this way :您现在可以通过以下方式调用 FooUtils.get() 方法:

...
FooProcessing fooAProcessing =  new FooAProcessing();
...
ArrayList<FooA> fooAs = FooAUtils.getFoo(context, category, fooAProcessing);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM