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 ?

2
  • 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) Commented Mar 11, 2014 at 18:27
  • Agreed this is a duplicate. SeaPlane is basically Pegasus in this answer stackoverflow.com/a/21824485/1168342 Commented Mar 12, 2014 at 16:43

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.