If you want to dynamically add new algorithms you might want to take a look at spi. https://docs.oracle.com/javase/tutorial/ext/basics/spi.html. These approaches mean that all algorithms must be initialisable, if one fails to construct none is usable.
With a textfile you register implementations of an interface and resolve these implementations by:
ServiceLoader<Algorithm> algorithms = ServiceLoader.load(Algorithm.class);
for (Algorithm algorithm : algorithms) {
if (algorithm.getId().equals(num)) {
return algorithm;
}
}
throw new IllegalArgumentException("Algorithm with num " + num + " does not exist");
That will return an Iterable for all implementations of that algorithm. You can loop through them to find the correct one.
You might want to store/cache the algorithms in a Map if you resolve them often in one run of your application.
This map can also be manually created if you dont want to use spi.
private static final Map<Integer, Algorithm> ALGORITHMS;
static {
Map<Integer, Algorithm> algs = new HashMap<>();
algs.put(1, new Alg1());
algs.put(2, new Alg2());
algs.put(3, new Alg3());
ALGORITHMS = Collections.unmodifiableMap(algs);
}