-1

如何使用 java 示例代码使用 Android 和 Hilt/Dagger 的工厂方法。这种设计模式在 Android Hilt/Dagger 中是否可行以及如何实现。我在网上找不到好的解决方案

谢谢约翰

public class ScannerFactory {

    private ScannerFactory() {
    }

    /**
     * Get the scanner device
     *
     * @param scannerType - The scanner type, one of A or B
     * @param context     - The apps context
     * @return
     */
    public static ScannerDevice getScannerDevice(final String scannerType, final Context context) {
        if (scannerType.equals("A")) {
            return new DeviceA(context);
        } else if (scannerType.equals("B")) {
            return new DeviceB(context);
        }
        throw new IllegalArgumentException("Wrong device");
    }
}
4

1 回答 1

0

从您的 javadoc 来看,您需要Application Context(而不是Acitivity上下文)。所以你应该这样做:

@Singleton
public class ScannerFactory {

    private final Context context;

    @Inject
    public ScannerFactory(@ApplicationContext Context context) {
        this.context = context;
    }

    /**
     * Get the scanner device
     *
     * @param scannerType - The scanner type, one of A or B
     * @return
     */
    public static ScannerDevice getScannerDevice(final String scannerType) {
        if (scannerType.equals("A")) {
            return new DeviceA(context);
        } else if (scannerType.equals("B")) {
            return new DeviceB(context);
        }
        throw new IllegalArgumentException("Wrong device");
    }
}

然后当你想使用它时,你可以使用 Hilt 遵循依赖项的常规规则Injecting。所以例如:

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {

    @Inject
    ScannerFactory scannerFactory;

    //... rest of the Activity code
}
于 2020-08-05T10:38:13.527 回答