I have a vehicle class, and nice implmented Ship and Plane to check for safety, each class implementing its own safetycheck. World was good.
interface Vehicle {
public void safetyCheck();
}
class Ship implements Vehicle {
@Override
public void safetyCheck() {
//check if number of lifeboats >= number of passengers
}
}
class Plane implements Vehicle {
@Override
public void safetyCheck() {
//check if oxygen mask is in place.
}
}
But soon a hybrid called seaplane was needed which duplicated safety checks of Ship
and Plane
class SeaPlane implements Vehicle {
@Override
public void safetyCheck() {
//check if oxygen mask is in place.
// &&
//check if number of lifeboats >= number of passengers
}
}
Which design patterns help in such particular scenarios to reduce code redundancy and make implementation cleaner ?
Which design patterns benefit from the multiple inheritances? Explanation: Adapter and observer patterns benefit from the multiple inheritances.
Composition and Interface Inheritance are the usual alternatives to classical multiple inheritance.
Multiple inheritance is useful when a subclass needs to combine multiple contracts and inherit some, or all, of the implementation of those contracts. For example, the AmericanStudent class needs to inherit from both the Student class and the American class.
Java doesn't support multiple inheritances in classes because it can lead to diamond problem and rather than providing some complex way to solve it, there are better ways through which we can achieve the same result as multiple inheritances.
Without establishing a new interface or class for this case you could use the Composition over Inheritance principle.
So your SeaPlane
could look like this:
class SeaPlane implements Vehicle {
private Vehicle plane,
ship;
@Override
public void safetyCheck() {
plane.safetyCheck();
ship.safetyCheck()
}
}
With a constructor taking a Plane
and a Ship
object.
You could apply the strategy pattern to separate some behavior of a component from the components definition. Then you could use these behaviors in multiple classes in order to avoid redundancy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With