Factory pattern in PHP - Time & Space Complexity
We want to understand how the time it takes to create objects using the factory pattern changes as we create more objects.
How does the work grow when we ask the factory to make many objects?
Analyze the time complexity of the following code snippet.
class Car {
public function drive() {
echo "Driving a car\n";
}
}
class CarFactory {
public function createCar() {
return new Car();
}
}
$factory = new CarFactory();
for ($i = 0; $i < $n; $i++) {
$car = $factory->createCar();
$car->drive();
}
This code creates $n car objects using a factory and calls a method on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new Car object inside the loop.
- How many times: Exactly $n times, once per loop iteration.
Each time we increase $n, the number of cars created grows the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 car creations and drives |
| 100 | 100 car creations and drives |
| 1000 | 1000 car creations and drives |
Pattern observation: The work grows directly in proportion to the number of objects created.
Time Complexity: O(n)
This means the time to create and use cars grows linearly as we ask for more cars.
[X] Wrong: "Using a factory makes object creation instant or constant time no matter how many objects."
[OK] Correct: Each object still needs to be created one by one, so time grows with the number of objects.
Understanding how object creation scales helps you explain design choices clearly and shows you think about efficiency in real code.
"What if the factory cached and reused objects instead of creating new ones each time? How would the time complexity change?"