-1

How can I have a Factory method using Android and Hilt/Dagger using the java example code. Is this design pattern possible in Android Hilt/Dagger and how to implement. I can not find a good solution on the web

Thanks John

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");
    }
}
Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
baliman
  • 588
  • 2
  • 8
  • 27

1 Answers1

0

Judging from your javadoc, you want the Application Context (and not Acitivity context). So you should do this like this:

@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");
    }
}

and then when you want to use that, you follow the regular rules for Injecting dependencies using Hilt. So e.g.:

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity {

    @Inject
    ScannerFactory scannerFactory;

    //... rest of the Activity code
}
Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132