Behavioral patterns (Observer, Strategy, Command) in Software Engineering - Time & Space Complexity
Behavioral design patterns help organize how objects interact and change behavior. Analyzing their time complexity shows how the cost of these interactions grows as the number of objects or commands increases.
We want to understand how the execution time changes when using Observer, Strategy, or Command patterns as the system grows.
Analyze the time complexity of notifying observers in the Observer pattern.
class Subject:
def __init__(self):
self.observers = []
def register(self, observer):
self.observers.append(observer)
def notify(self, message):
for observer in self.observers:
observer.update(message)
This code shows a subject notifying all registered observers by calling their update method.
Look at what repeats when notify is called.
- Primary operation: Looping through all observers to call update.
- How many times: Once for each observer registered.
As the number of observers grows, the notify method calls update more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 update calls |
| 100 | 100 update calls |
| 1000 | 1000 update calls |
Pattern observation: The number of operations grows directly with the number of observers.
Time Complexity: O(n)
This means the time to notify observers grows linearly with how many observers there are.
[X] Wrong: "Notifying observers happens instantly no matter how many there are."
[OK] Correct: Each observer must be updated one by one, so more observers mean more work and more time.
Understanding how behavioral patterns affect time helps you explain design choices clearly. It shows you can think about both design and performance, a valuable skill in real projects.
What if the notify method used multiple threads to update observers in parallel? How would the time complexity change?