I’m creating a abstractFactory class and I want to be able to send the concrete factory as a parameter. This way I can remove the if/else chain inside my abstract class.
My problem is I’m not sure how to typecast it back to the concrete class within my abstract class in order to call the createVehicle() method.
car = UniversalVehicleFactory.getFactory().createVehicle(CarFactory);
plane = UniversalVehicleFactory.getFactory().createVehicle(PlaneFactory);
Inside UniversalVehicleFactory I have the method createVehicle which is the method I’m having a problem with. What I’m trying to achieve is: take the parameter, determine its class and cast it to that, then call its internal createVehicle class.
public Vehicle createVehicle(AbstractFactory factory) {
// I want to take factory,
// cast it to the concrete factory, and
// call createMethod() on the factory
return factory.getInstance().createVehicle();
}
Help with this problem much appreciated!
I’ll answer your question, but I’m curious why you want a universal factory to call a method of an abstract factory, if indeed you have to supply an instance of that factory as a parameter; you would be better off just invoking the creation method of the abstract factory directly.
Generics were invented for this purpose.
You’ll notice that UniversalVehicleFactory doesn’t implement Factory< T >.