One situation where I personally find separate Factory classes to make sense is when the final object you are trying to create relies on several other objects. E.g, in PHP: Suppose you have a House
object, which in turn has a Kitchen
and a LivingRoom
object, and the LivingRoom
object has a TV
object inside as well.
The simplest method to achieve this is having each object create their children on their construct method, but if the properties are relatively nested, when your House
fails creating you will probably spend some time trying to isolate exactly what is failing.
The alternative is to do the following (dependency injection, if you like the fancy term):
$TVObj = new TV($param1, $param2, $param3);
$LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
$KitchenroomObj = new Kitchen($param1, $param2);
$HouseObj = new House($LivingroomObj, $KitchenroomObj);
Here if the process of creating a House
fails there is only one place to look, but having to use this chunk every time one wants a new House
is far from convenient. Enter the Factories:
class HouseFactory {
public function create() {
$TVObj = new TV($param1, $param2, $param3);
$LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
$KitchenroomObj = new Kitchen($param1, $param2);
$HouseObj = new House($LivingroomObj, $KitchenroomObj);
return $HouseObj;
}
}
$houseFactory = new HouseFactory();
$HouseObj = $houseFactory->create();
Thanks to the factory here the process of creating a House
is abstracted (in that you don't need to create and set up every single dependency when you just want to create a House
) and at the same time centralized which makes it easier to maintain. There are other reasons why using separate Factories can be beneficial (e.g. testability) but I find this specific use case to illustrate best how Factory classes can be useful.