I’m trying to write a driving simulation program and I need some help on the design. I have a interface called RoadObjects which for now contains vehicles and mammals. I need to implement different kind of cars such as trucks, sedans, semis. they have some methods in common and some unique. Later on, I will add other kinds of vehicles and mammals. I don’t want to use inheritance and I am trying to do this according to design principles and patterns such as open-closed principle and factory. Now my question is, should I design it like this:
RoadObject interface
Vehicle extends RoadObject
Mammal extends RoadObject
SedanImpl implements Vehicle
TruckImpl implements Vehicle
People implements Mammal
…
…
or should I just not have vehicle and people interface and do this?
RoadObject interface
SedanImpl implements RoadObject
TruckImpl implements RoadObject
People implements RoadObject
New question:
I want to use a factory pattern, to chose which kind of vehicles for example. So I make a VechicleImpl and VechicleImplFactory so it might look like this:
RoadObject interface
Vehicle extends RoadObject
VehicleImpl implements Vehicle
Mammal extends RoadObject
SedanImpl implements Vehicle
TruckImpl implements Vehicle
People implements Mammal
Is this kind of bad design? Because VehicleImpl will have a lot of duplicate methods of SedanImpl,TruckImpl etc. Or if I wanted to have an factory that createVehicle, where should this be?
Both approaches are valid, whether you need an explicit abstraction for vehicles depends on your requirements.
SedanImpl,TruckImpletc. may share some features common to vehicles but not to humen/animals:As you tagged this in Java common
abstractclasses may be useful as well:So that
TruckImplcan inherit fromAbstractVehicle: