Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which design pattern to use when multiple inheritance is needed in java [duplicate]

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 ?

like image 624
JavaDeveloper Avatar asked Mar 11 '14 18:03

JavaDeveloper


People also ask

Which design patterns benefit from the multiple inheritance?

Which design patterns benefit from the multiple inheritances? Explanation: Adapter and observer patterns benefit from the multiple inheritances.

What is an alternative design to avoid multiple inheritance?

Composition and Interface Inheritance are the usual alternatives to classical multiple inheritance.

When multiple inheritance concept should be used?

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.

What would happen if multiple inheritance is possible in Java?

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.


2 Answers

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.

like image 99
Zhedar Avatar answered Nov 15 '22 17:11

Zhedar


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.

like image 21
Dennis Kassel Avatar answered Nov 15 '22 17:11

Dennis Kassel