Lighten a specific aspect of:
Factory Pattern. When to use factory methods?
At my team there was a discussion about the factory design pattern.
In our project we have some Factories that are build like this one:
class ProductFactory {
const PRODUCT_A = 'product_a';
const PRODUCT_B = 'product_b';
const PRODUCT_C = 'product_c';
private static $classMapping = array(self::PRODUCT_A => 'A',
self::PRODUCT_B => 'B',
self::PRODUCT_C => 'C');
public function create($productConstant) {
$className = self::$classMapping[$productConstant];
return new $className();
}
}
The discussion was about the use of this factory.
If I never define a product dynamically and always define the product I like to recive from it, is there any need to use this pattern?
The advantage of factories is that they decouple code. Take your class
Foo, which needs an instance ofA:The class
Foois now coupled to the classA, because it hardcodes the classname in its source. You cannot provide an alternative implementation ofAtoFooif you wanted to, for example to mockAin tests. Here’s where factories come in:You can now inject any kind of
AintoFoowhen needed, you have decoupled the two classes.That’s what factories are for. Use them when appropriate. If there’s no problem coupling
FootoA, more power to you.