Answer the question
In order to leave comments, you need to log in
Which pattern is best for getting rid of a lot of ifs?
Hello
The program has a bunch of objects of various classes (airplanes, boats, helicopters, tanks, cars, trucks) that connect various
interfaces (drive, fly, shoot, transport). Accordingly, in the code, you need to use a bunch of conditions to understand what kind of object
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();
}
Answer the question
In order to leave comments, you need to log in
Or make the interface separate or look towards the Adapter pattern
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question