V
V
vrazbros2017-10-04 19:34:27
PHP
vrazbros, 2017-10-04 19:34:27

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();    
}

I can not understand what is the best technique to use to get rid of a bunch of if in the program? since the methods of an object can be different, polymorphism is not suitable, you need to know exactly
which class object is used.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
synapse_people, 2017-10-04
@synapse_people

Or make the interface separate or look towards the Adapter pattern

G
grafgeest, 2017-10-05
@grafgeest

Usually recommend the Strategy pattern

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question