Pergunta

I'm busy playing around with some training material to help teach some of the juniors the factory pattern.

Whilst writing the example, I can't help but think this might be an anti-pattern.

Lets say I have iVehicle which is implemented by iMotorVehicle which, subsequently is implemented by iCar, iBike and iTruck respectively.

Would it be considered an anti-pattern to call a VehicleFactory, whose sole responsibility is to produce a resultant of iVehicle which will then call the MotorVehicleFactory, producing iMotorVehicle to call the CarFactory to produce a result of iCar?

To me this feels like each of the factories are fulfilling their respective responsibilities without stretching to fulfill a responsibility that could be fulfilled by another.

Is this an anti-pattern?

Foi útil?

Solução

What you describe is basically the abstract factory pattern, combined with the facade pattern.

It is also something that follows logically when you iterate on abstracting away the creation of your vehicles. You start by abstracting away the fact that your Car needs an Engine and 4 instances of Wheel into a factory (and do the same for the other vehicles). Moving what is essentially a switch to select the correct Factory into a reusable layer it then a logical step.

Based on what you describe, for this (most likely fictional) example, I think it makes sense to add this layer. However (as Pieter B pointed out) it is important to find a good balance. A FactoryFactory is always a bad idea. A DatabaseConnectionFactory that selects the driver based on some input is usually a good idea. A key difference between the two is that a FactoryFactory will give you an intermediate, while a DatabaseConnectionFactory will clearly give you what you need - a DatabaseConnection.

So in summary, no, your VehicleFactory is not an anti-pattern.

Licenciado em: CC-BY-SA com atribuição
scroll top