dimanche 24 novembre 2019

How is the following design pattern a Factory method. I believe it is more of a Abstract Factory than factory method

How is the design pattern used in the following question a Factory method?. I suspect it is neither Factory Method nor Abstract Factory. It is a mix of both.

interface Vehicle { }
class Car implements Vehicle{ }       // Oil Vehicles
class Bus implements Vehicle{ }
class ElectricCar implements Vehicle{ } // ElectricVehicles
class ElectricBus implements Vehicle{ }

interface VehicleFactory{
  Vehicle make(int seats);
}

class OilVehicleFactory implements VehicleFactory{ // Oil vehicle Factory 
  @Override
  Vehicle make(int  seats){
     if(seats > 5){
        return new Bus();
     }
     else{
          return new Car();
    }
}

class ElectricVehicleFactory implements VehicleFactory{ // Electric Vehicle Factory
  @Override
  Vehicle make(int  seats){
     if(seats > 5){
        return new ElectricBus();
     }
     else{
          return new ElectricCar();
    }
}

class Client{                   // Cient Code
    boolean isElectric;

    void doSomething(){
     VehicleFactory  factory;
     if(isElectric){ 
       factory = new ElectricVehicleFactory();   
     }
     else{
       factory = new oilVehicleFactory();
    }

    Vehicle vehicle = factory.make(5);
}

I believe it is NOT a factory method as:

  1. It is using the interface VehicleFactory (which is used in Abstract Factory)

  2. It is creating families of products such as Oil vehicles and Electric Vehicle

  3. It doesn't use inheritance.

For the same reasons I believe that It is an Abstract factory method. But it doesn't use Composition for the factory.

What pattern is it exactly?

Thanks

Aucun commentaire:

Enregistrer un commentaire