I'm facing a design challenge where I have to switch based on the instance of an object. I have been told that it's a bad idea to use instanceof
operator in Java. Someone suggested visitor pattern, but in the scenario I'm facing switching has to be done based on one objects instance and not two. So I feel like it might overkill to use visitor pattern which is quite specific and confusing. Please suggest the right approach. Following is a sample
VehicleHandler ( Vehicle vehicle){
if( vehicle instanceof Car)
// Do something which cant be tied to Car's impl ( Dont want busiess logic to be in the class itself
else if(vehicle instanceof Bike)
// Do something
}
Car
and Bike
implement marker interface Vehicle
. There are many classes having functions which takes vehicle as arguments and will need to bifurcate in each of those classes such as VehicleTransformer
, VehicleValidator
etc. Those methods are doing completely unrelated actions. Please help me identify the right design pattern for this problem.
Aucun commentaire:
Enregistrer un commentaire