I'm looking for an improved solution to the following problem. I have an object, which is passed to a factory; the factory will inspect the object type, create another type, which it populates with data from the incoming object, and returns the new one.
...
public MyAbstractClass create(MyObject a) {
if (a instanceof A) {
A obj = (A) a;
return new MyAbstractClass_1 (obj.getField(), factoryField);
}
else if (a instanceof B) {
B obj = (B) a;
return new MyAbstractClass_2 (obj.getSomething(), obj.getSomethingElse(), factoryField);
}
}
Instances of the return type are treated generically afterwords. Going forward I need to support more types and if possible I'd like to avoid an instanceof solution. How can I improve this?