7

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 ?

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • 1
    I would create a common ancestor for `Plane`, `Ship` and `SeaPlane`, with a parameterized `safetyCheck`, then `Plane` call super with first value of param, `Ship` call super with another value of param and `SeaPlane` call twice, one with both param. (may be using an enum for the param) –  Mar 11 '14 at 18:27
  • Agreed this is a duplicate. SeaPlane is basically Pegasus in this answer stackoverflow.com/a/21824485/1168342 – Fuhrmanator Mar 12 '14 at 16:43

2 Answers2

9

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.

Zhedar
  • 3,480
  • 1
  • 21
  • 44
1

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.

Dennis Kassel
  • 2,726
  • 4
  • 19
  • 30
  • I dont think the strategy Pattern applies here, since you're not changing the object's type at runtime. You only want to reduce redundancy. – Zhedar Mar 11 '14 at 19:18