Creational patterns (Singleton, Factory, Builder) in Software Engineering - Time & Space Complexity
When using creational patterns like Singleton, Factory, and Builder, it's important to understand how the time to create objects grows as the program runs.
We want to know how the cost of creating objects changes when we create many of them.
Analyze the time complexity of creating multiple objects using a Factory pattern.
class Product {
constructor(name) {
this.name = name;
}
}
class ProductFactory {
createProduct(name) {
return new Product(name);
}
}
const factory = new ProductFactory();
for (let i = 0; i < n; i++) {
factory.createProduct(`Product${i}`);
}
This code creates n products using a Factory. Each product is a simple object with a name.
Look at what repeats when creating many objects.
- Primary operation: Calling
createProductto make a new object. - How many times: Exactly n times, once for each product.
Each new product takes about the same time to create, so total time grows as we make more products.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: The time grows directly with the number of objects created.
Time Complexity: O(n)
This means if you double the number of objects, the time to create them roughly doubles too.
[X] Wrong: "Using a Factory or Builder makes object creation instant or constant time regardless of how many objects."
[OK] Correct: Each object still needs to be created one by one, so total time grows with the number of objects, even if the pattern helps organize the code.
Understanding how object creation scales helps you explain design choices clearly and shows you grasp both design and performance, a useful skill in real projects.
What if the Factory cached and reused objects instead of creating new ones each time? How would the time complexity change?