Why design patterns solve recurring problems in Software Engineering - Performance Analysis
We want to understand how using design patterns affects the time it takes to solve common software problems.
How does applying a design pattern change the work needed as problems grow bigger or more complex?
Analyze the time complexity of using a design pattern to solve a recurring problem.
class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
# Usage
obj1 = Singleton()
obj2 = Singleton()
This code ensures only one instance of a class is created, solving the problem of multiple objects where only one is needed.
Look for repeated checks or object creations.
- Primary operation: Checking if an instance already exists before creating a new one.
- How many times: Each time the class is instantiated, the check runs once.
As the number of times the class is used grows, the check happens each time but object creation happens only once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks, 1 creation |
| 100 | 100 checks, 1 creation |
| 1000 | 1000 checks, 1 creation |
Pattern observation: The number of checks grows linearly, but the costly creation happens only once.
Time Complexity: O(n)
This means the time grows linearly with how many times you request the object, but the expensive part happens just once.
[X] Wrong: "Using a design pattern always makes the program slower because it adds extra steps."
[OK] Correct: Design patterns often add small checks that save much more time or effort overall by preventing repeated costly actions.
Understanding how design patterns affect time helps you explain why they are useful beyond just code style—they solve problems efficiently as programs grow.
"What if the Singleton pattern created a new instance every time instead of reusing one? How would the time complexity change?"