vendredi 27 janvier 2017

Mixing Builders and Factory pattern is it a good idea?

I have an object Carconstructed using builder pattern. Issue was a lot of code redundancy.

    Car.Builder builder = new Car().Builder("Mercedes");
    builder.numDoors(carConfig.getNumDoors()
    builder.engineType(carConfig.getEngineType())
    builder.isManual(isManual)
    builder.build())

    Car.Builder builder = new Car().Builder("BMW");
    builder.numDoors(carConfig.getNumDoors()
    builder.engineType(carConfig.getEngineType())
    builder.isManual(isManual)
    builder.build())

    Car.Builder builder = new Car().Builder("FlyingCar");
    builder.numDoors(carConfig.getNumDoors()
    builder.engineType(carConfig.getEngineType())
    builder.wing(TypeName)
    builder.build())

So thought of an idea to reduce code clutter using factory pattern. Using the factory below, I can create Car easily.

Car mercedes = CarFactory.createNonFlyingCar("Mercedes");

Car bmw = CarFactory.createNonFlyingCar("BMW");

Car flyCar = CarFactory.createFlyingCar("FlyingCarBrand");

public class CarFactory {

    // brand can be BMW or Mercedes or Audi etc.
    public static Car createNonFlyingCar(String brand, CarConfiguration carConfig, Engine engine) {
        Car.Builder builder = new Car().Builder(brand);
        append(builder, carConfig.getNumDoors(), carConfig.getEngineType(), engine.isManual()).build();
    }

    public static Car createFlyingCar(CarConfiguration carConfig, Wings wings) {
        Car.Builder builder = new Car().Builder("NewFlyingCar");
        append(builder, carConfig.getNumDoors(), carConfig.getEngineType()).wings(wing.getType()).build(); // added extra 'wings' method here.
    }

    // overload append.
    private static void append(
        Car.Builder builder,
        int numDoors,
        Sting engineType,
        boolean isManual;
    )
    {
        return append(builder, numDoors, engineType).isManual(isManual);

    }

    private static void append(
        Car.Builder builder,
        int numdoors,
        String engineTye
    )
    {
        return builder.numdoors(numdoors).engineType(engineTyoe);
    }

}

  1. One thing which I did in the factory was overloading append method. When common fields were involved, used them. Eg: numdoors and enginetype was shared between flying and nonflying cars. so I created an append(numdoors, engineType) which was called by append with more param.

  2. Next thing is the wing which was unique to flying car was left out of append.

Is this a known pattern ? Good ? Bad ? And Why ?

Aucun commentaire:

Enregistrer un commentaire