Consider the following function:
public IVehicleProcessor GetVehicle(VehicleType vehicleType, string regNo) {
if (vehicleType == VehicleType.Car)
return new CarProcessor(regNo);
if (vehicleType == VehicleType.Van)
return new VanProcessor(regNo);
if (vehicleType == VehicleType.Truck)
return new TruckProcessor(regNo);
// the list goes on.
return null;
}
And then in another (“child”) project
public enum VehicleType {
Car,
Van,
Truck,
// etc.
}
Is there a way of re-writing this method so that it doesn’t rely on a bunch of if
statements? (And I don’t mean by just changing it to a switch
). This code will be customised a bit, and let’s say I wanted to add, say, a Bus, I’d like to be able to just create a BusProcessor : IVehicleProcessor
and add Bus
to the VehicleType
enum and GetVehicle()
would just know what to do. Perhaps using Reflection or something?
For example, I was thinking maybe having the VehicleType
as a property in IVehicleProcessor
such that each ‘processor’ class would return its own Vehicle type, but I don’t know how I could access that from GetVehicle()
– especially as it would have to be done before it’s instantiated. Could also make it a static property, but then how to enforce that using the IVehicleProcessor
interface?