I'm using the factory pattern to create instances, and want to initialise these instances with different objects. At the moment I'm simply casting the object, but this doesn't feel right.
public interface IGenerator {
public IGeneratedObject generate();
}
public class FirstGenerator implements IGenerator {
private List<FirstObject> list;
public FirstGenerator(List<FirstObject> list) {
this.list = list;
}
public IGeneratedObject generate() {
return doSomeStuff(list);
}
}
public class SecondGenerator implements IGenerator {
private UnrelatedObject obj;
public SecondGenerator(UnrelatedObject obj) {
this.obj = obj;
}
public IGeneratedObject generate() {
return doOtherThingsStuff(obj);
}
}
public class GeneratorFactory {
public static IGenerator createGenerator(GeneratorType type, Object object) {
switch (type) {
case FIRST:
return new FirstGenerator((List<FirstObject>) object);
case SECOND:
return new SecondGenerator((UnrelatedObject) object);
}
return null;
}
}
Usage would then be as follows:
IGenerator gen1 = GeneratorFactory.createGenerator(GeneratorType.FIRST, listOfFirstObjects);
IGenerator gen2 = GeneratorFactory.createGenerator(GeneratorType.SECOND, unrelatedObj);
FirstObject and UnrelatedObject aren't related at the moment - no common base class or interfaces.
In the factory method, the compiler of course shows an 'Unchecked cast from...' warning.
Is there a better way? It seems like a situation where generics could be used, but is this unfeasible due to the objects not being related?
IGeneratorregardless of the input data. I'm afraid I'm not familiar enough with generics on how to achieve this