mercredi 15 août 2018

Why to use Factory method pattern instead of Simple factory

Im trying to understand when to use Factory method pattern compared to Simple factory, I know how each implements but I don't exactly get the point of it.

Let's assume I have client that provides string(name of the car) and based on that string, factory provides object.

I know that method factory satisfies open/closed principle and if I had new car brand for example Mercedes, I would have to edit switch case and add new brand and that would be bad practice. But then with Factory method my factory can't decide on which object to make because there is no switch case. I guess I'm missing a point here. Maybe I should use factory method if I had diffrent logic/strategy on creating car object, maybe one that makes random car object and one that takes string and makes object based on that string.

Also would It be a good practice if I used in Factory Method getCar() function and do some more logic there, like maybe car.tuneEngine() etc. before returning ready to use object?

Simple factory

public class FordCar extends Car {

    public FordCar() {
        super("Ford", "Mondeo", 1.6);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void move() {
        System.out.println("Ford moves");

    }

}

public class CarFactory {

    public Car getCar(String brand) {
        switch (brand) {
        case "ferrari":
            return new FerrariCar();
        case "ford":
            return new FordCar();
        default:
            return null;

        }
    }
}

public class Client {

    public static void main(String[] args) {

        //Simple factory
        CarFactory carFactory = new CarFactory();
        Car clientSimpleCar = carFactory.getCar("ford");
        clientSimpleCar.move();     
    }
}

Factory method pattern

public abstract class CarMethodFactory {

    public Car getCar(){
        Car car = createCar();
        return car;
    }

    public abstract Car createCar();

}

public class FordMethodFactory extends CarMethodFactory{

    @Override
    public Car createCar() {
        return new FordCar();
    }

}

public class Client {

    public static void main(String[] args) {

        CarMethodFactory carMethodFactory = new FordMethodFactory();
        Car clientMethodCar = carMethodFactory.getCar();
        clientMethodCar.move();

    }

}

Aucun commentaire:

Enregistrer un commentaire