When to consider the use of the factory design pattern?

The factory pattern is a good solution for those cases in which the main part of the app needs to manage the objects and not create them.

Let's demonstrate this with a CarOrder class that handles cars orders. Each time a new car is ordered, we call the order method and pass the car type as a parameter ('r' or 's' model). The order method then makes a new car object (based on the parameter) and adds the newly created car object to the $carOrders array that stores the list of cars that were ordered.

class CarOrder { protected $carOrders = array(); protected $car; // Order & make the car in the same method???! public function order($model=null) { if(strtolower($model) == 'r') $this ->car = new CarModelR(); else $this ->car = new CarModelS(); $this ->carOrders[] = $this ->car->getModel(); } public function getCarOrders() { return $this ->carOrders; } }

In this textbook example, it does not seem like a bad idea to mix between the code that makes objects and the code that manages them. However, most of the code in real life is much more complex. For example, different car models may very well need different chassis; the higher-end model may have extra comfortable seats or be a convertible, etc. It's too much responsibility for a method whose sole purpose is to order cars to handle their manufacturing as well.