0
0
Software Engineeringknowledge~5 mins

Creational patterns (Singleton, Factory, Builder) in Software Engineering - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Creational patterns (Singleton, Factory, Builder)
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

Look at what repeats when creating many objects.

  • Primary operation: Calling createProduct to make a new object.
  • How many times: Exactly n times, once for each product.
How Execution Grows With Input

Each new product takes about the same time to create, so total time grows as we make more products.

Input Size (n)Approx. Operations
1010 object creations
100100 object creations
10001000 object creations

Pattern observation: The time grows directly with the number of objects created.

Final Time Complexity

Time Complexity: O(n)

This means if you double the number of objects, the time to create them roughly doubles too.

Common Mistake

[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.

Interview Connect

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.

Self-Check

What if the Factory cached and reused objects instead of creating new ones each time? How would the time complexity change?