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?"
Practice
Factory Pattern in PHP?Solution
Step 1: Understand the role of the Factory Pattern
The Factory Pattern is designed to create objects while hiding the details of how they are created.Step 2: Compare options with the pattern's purpose
Only To create objects without exposing the creation logic to the client describes creating objects without exposing creation logic, which matches the Factory Pattern.Final Answer:
To create objects without exposing the creation logic to the client -> Option AQuick Check:
Factory Pattern = Object creation hiding [OK]
- Confusing factory pattern with database operations
- Thinking it handles input validation
- Assuming it performs calculations
Solution
Step 1: Identify typical factory method signature
Factory methods are often static so they can be called without creating an instance.Step 2: Check options for static keyword
Only public static function create() {} usespublic static function create(), which is the common factory method style.Final Answer:
public static function create() {} -> Option AQuick Check:
Factory method is usually static [OK]
- Omitting static keyword for factory methods
- Using private visibility which blocks access
- Not specifying visibility (defaults to public but less clear)
class Book { }
class ProductFactory {
public static function create($type) {
if ($type === 'Book') {
return new Book();
}
return null;
}
}
$product = ProductFactory::create('Book');
echo get_class($product);Solution
Step 1: Analyze the factory method call
The callProductFactory::create('Book')checks if the type is 'Book' and returns a newBookobject.Step 2: Check the output of get_class
Since the returned object is an instance ofBook,get_class($product)returns "Book".Final Answer:
Book -> Option CQuick Check:
Factory returns Book object, get_class = Book [OK]
- Expecting factory class name instead of product class
- Assuming null is returned
- Thinking code throws error due to missing class
class Car {}
class VehicleFactory {
public static function create($type) {
if ($type = 'Car') {
return new Car();
}
return null;
}
}Solution
Step 1: Check the if condition syntax
The condition uses=which assigns 'Car' to $type instead of comparing it.Step 2: Understand impact of assignment in condition
Assignment always returns true, so the if block always runs regardless of input, which is a logic error.Final Answer:
Using assignment (=) instead of comparison (==) in the if condition -> Option BQuick Check:
Use == for comparison, not = [OK]
- Confusing = and == in if statements
- Thinking static method is wrong here
- Assuming missing return type causes error
Solution
Step 1: Understand the Factory Pattern goal
The pattern centralizes object creation in one place, hiding details from the client.Step 2: Evaluate options for best factory design
Create a VehicleFactory with a static create method that returns new Car, Bike, or Truck objects based on input uses one factory class with a method that creates different vehicle objects based on input, which is the classic factory pattern.Step 3: Compare other options
Create separate factory classes for CarFactory, BikeFactory, and TruckFactory each with their own create method splits factories, which is more like Abstract Factory or multiple factories, not simple Factory Pattern. Create one class Vehicle with properties to switch between Car, Bike, and Truck behaviors mixes behaviors in one class, breaking single responsibility. Use global functions to create Car, Bike, and Truck objects directly uses global functions, which is not object-oriented.Final Answer:
Create a VehicleFactory with a static create method that returns new Car, Bike, or Truck objects based on input -> Option DQuick Check:
Single factory method creates varied objects [OK]
- Splitting factories unnecessarily
- Mixing multiple behaviors in one class
- Using global functions instead of classes
Ready to prove it?
Pass the test and this pattern moves unknown
