I came across this problem in an interview where I was asked to design a simple architecture for Vehicle infrastructure for all vehicles.
Problem statement was something like - Consider a base class 'Vehicle' for all kinds of vehicles (cars, trucks, bikes, autos, cycles ...). Now we have multiple requirements for different kind of vehicles- Eg. Car, Jeep, .. have AC whereas bike, cycles, trucks does not have AC.
Also we have a long list of vehicles(all vehicles) and we specifically want to perform some operations based on whether this vehicle has ac or not. How can we design this.
I was able to come up with an approach where I created an interface for AC Functionality and have vehicles that have ac implement these.
class Vehicle
{
}
inteface IACFunctionality
{
void PerformSomeOperation();
}
class Car : Vehicle, IACFunctionality
{
//Implementation
}
class Bike : Vehicle
{
//No implementation for ac
}
public void UpdateAllACDevices(List<Vehicle> vehicles)
{
// Check if vehicle type implements IACFunctionality and perform operation
foreach(var vehicle in vehicles)
{
IACFunctionality acVehicle = vehicle as IACFunctionality;
if(acVehicle != null)
acVehicle.PerformSomeOperation();
}
}
This was all good until he asked me - consider if few cars did not have AC. How will you integrate this change ?
I decided to go ahead with bit shady approach to have 2 separate classes for Car - one that implemented IACFunctionality and one that didn't.
class ACCar : Vehicle, IACFunctionality
{}
class NonACCar : Vehicle
{}
Now he further asked what if there are multiple such requirements like AC - music system, sunroof, etc. I realized this wont fit according to my approach, but based on interface segregation principle, I didn't want to have something defined for a class which it does not require.
What would be correct approach to proceed with this design ?
Aucun commentaire:
Enregistrer un commentaire