Which template is better suited for getting rid of many if?

Hi

The program has a bunch of objects of various classes (planes, boats, helicopters, tanks, cars, trucks) that connect different
interfaces (to drive, to fly, to shoot, to carry). Correspondingly, in the code it is necessary to use a lot of terms to understand what objekto
and what method can be called:
foreach($vehicles as $vehicle) {
switch($vehicle->type)
{
 case 'car':
$vehicle->move();
$vehicle->closeDoor();
break;
 case 'ship':
$vehicle->move();
$vehicle->swim();
break;
 case 'airplane':
$vehicle->fly();
$vehicle->landing();
break;
 case 'tank':
$vehicle->move();
$vehicle->stop();
$vehicle->fire();
break;
}
 $vehicle->stop(); 
}


I can not understand what is better to use the technique to get rid of the pile if in the program ? TC methods of the object can be different polymorphism is not suitable, we need to know exactly
the object of the class is used.
June 14th 19 at 20:04
3 answers
June 14th 19 at 20:06
As an option you need a common interface to all Vehicle actions, something like

interface VehicleActionInterface {
 public function perform();
}


then, each Vehicle must implement the method perform about as from your example

class ShipVehicle extends Vehicle implements VehicleActionInterface {
 public function perform() {
$this->move();
$this->swim();
}
}


Then having a common interface you can easily walk around all Vehicle and to cause them perform something like this:

foreach($vehicles as $vehicle) { 
$vehicle->perform();
}
June 14th 19 at 20:08
Or make a separate interface or look in the direction of the pattern Adapter
June 14th 19 at 20:10
Usually recommended pattern Strategy

Find more questions by tags OOPPatterns of designingPHP